From dffe4de3533311ed8e076a364909f7965d4e39e7 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 07:48:29 -0700 Subject: [PATCH 01/13] MP-01: one table of source kinds reframe.source.kinds is the one table of what each file in a mainframe snapshot is, taken from AWS Transform's list of source file types (its user guide's page on mainframe source artifacts), with `.pli`, which Reframe already read. - A known extension decides, in any case: `.CBL` is `.cbl`; `.cobol` and `.pl1` are COBOL and PL/I. A member with no extension or `.txt` is classed by its content, as AWS Transform classes it: COBOL divisions, copybook data entries, JCL JOB and PROC statements, BMS, CSD, IMS DBD, PSB and Stage 1 macros, DCLGEN, DDL, REXX, PL/I, Assembler and an IDCAMS LISTCAT listing. - The reconciliation's source files and the design's readers (the inventory, the flow and the data contracts) use it in place of their own suffix lists. - Defect fixed: the flow followed COPY only into folders whose name starts with `cpy` (CardDemo's layout), so copybooks in `copy/` (Bank-of-Z) or `copybooks/` (AWS's example layout) were never read. The flow now finds copybooks wherever they are, and those in a `cpy` folder still come first when two share a name. Tests: a package laid out as AWS Transform documents it, with upper-case extensions, members with no extension and `.txt`, gives the same programs, copybooks, maps, transactions, links and keys as the usual layout, and the reconciliation reads the same source files. Prepared with AI assistance. --- src/reframe/design/contracts.py | 21 ++-- src/reframe/design/flow.py | 16 ++- src/reframe/design/inventory.py | 14 +-- src/reframe/reconcile/inputs.py | 7 +- src/reframe/source/kinds.py | 169 ++++++++++++++++++++++++++++++++ tests/source/test_kinds.py | 102 +++++++++++++++++++ 6 files changed, 300 insertions(+), 29 deletions(-) create mode 100644 src/reframe/source/kinds.py create mode 100644 tests/source/test_kinds.py diff --git a/src/reframe/design/contracts.py b/src/reframe/design/contracts.py index e03b97a0..5a114dc9 100644 --- a/src/reframe/design/contracts.py +++ b/src/reframe/design/contracts.py @@ -33,23 +33,22 @@ # ---- copybooks --------------------------------------------------------------------------------------------------------- def copybooks(legacy: Path) -> dict[str, Path]: - """Data copybooks by name: every .cpy file wherever it is (some codebases keep them beside the programs), and the files - without an extension in cpy folders. The screen copybooks are left out: those in a cpy-bms folder, and those named - after a BMS mapset in the snapshot.""" - files = sorted(p for p in legacy.rglob("*") if p.is_file()) - maps = {p.stem.upper() for p in files if p.suffix.lower() == ".bms"} + """Data copybooks by name: every copybook wherever it is (some codebases keep them beside the programs), by its + extension or its content, and the files without an extension in cpy folders (reframe.source.kinds). The screen + copybooks are left out: those in a cpy-bms folder, and those named after a BMS mapset in the snapshot.""" + from reframe.source import kinds + maps = {p.stem.upper() for p in kinds.files(legacy, "bms")} found: dict[str, Path] = {} - for p in files: - folder = p.parent.name.lower() - if "bms" in folder or p.stem.upper() in maps: + for p in kinds.copybooks(legacy): + if "bms" in p.parent.name.lower() or p.stem.upper() in maps: continue - if p.suffix.lower() == ".cpy" or (p.suffix == "" and folder.startswith("cpy")): - found.setdefault(p.stem.upper(), p) + found.setdefault(p.stem.upper(), p) return found def programs(legacy: Path) -> dict[str, Path]: - return {p.stem.upper(): p for p in sorted(legacy.rglob("*")) if p.is_file() and p.suffix.lower() in (".cbl", ".cob")} + from reframe.source import kinds + return {p.stem.upper(): p for p in kinds.files(legacy, "cobol")} def copied(text: str) -> list[str]: diff --git a/src/reframe/design/flow.py b/src/reframe/design/flow.py index b9e577d5..063e71ef 100644 --- a/src/reframe/design/flow.py +++ b/src/reframe/design/flow.py @@ -136,8 +136,13 @@ def _first(pattern: str, text: str, default: str = "") -> str: def _copybooks(legacy: Path) -> dict[str, Path]: - return {p.stem.upper(): p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() in (".cpy", "") - and p.parent.name.lower().startswith("cpy")} + """Copybooks by name, from Reframe's table of source kinds (MP-01): wherever they are, by extension or content. Those in + a folder whose name starts with `cpy` come first, as before, when two share a name.""" + from reframe.source import kinds + found: dict[str, Path] = {} + for p in sorted(kinds.copybooks(legacy), key=lambda p: (not p.parent.name.lower().startswith("cpy"), p.as_posix())): + found.setdefault(p.stem.upper(), p) + return found def read_program(path: Path, legacy: Path, copybooks: dict[str, Path]) -> Program: @@ -231,8 +236,9 @@ def resolve(program: Program, expr: str, depth: int = 0) -> list[dict[str, Any]] # ---- the flow ---------------------------------------------------------------------------------------------------------- def transactions(legacy: Path) -> list[dict[str, Any]]: + from reframe.source import kinds found = [] - for path in sorted(p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() == ".csd"): + for path in kinds.files(legacy, "csd"): text = path.read_text(errors="replace") for m in re.finditer(r"DEFINE\s+TRANSACTION\((\w+)\)(.*?)(?=\bDEFINE\b|\Z)", text, re.S | re.I): program = re.search(r"\bPROGRAM\((\w+)\)", m.group(2), re.I) @@ -273,8 +279,8 @@ def _branch(program: Program, line: int) -> tuple[int, int]: def flow(legacy: Path, screens: dict[str, Any]) -> dict[str, Any]: copybooks = _copybooks(legacy) - programs = {p.stem.upper(): read_program(p, legacy, copybooks) for p in sorted(legacy.rglob("*")) - if p.is_file() and p.suffix.lower() in (".cbl", ".cob")} + from reframe.source import kinds + programs = {p.stem.upper(): read_program(p, legacy, copybooks) for p in kinds.files(legacy, "cobol")} by_tran: dict[str, dict[str, Any]] = {} trans = transactions(legacy) for t in trans: diff --git a/src/reframe/design/inventory.py b/src/reframe/design/inventory.py index 6e517a73..ce71923a 100644 --- a/src/reframe/design/inventory.py +++ b/src/reframe/design/inventory.py @@ -19,9 +19,6 @@ from pathlib import Path from typing import Any -BMS_SUFFIXES = (".bms",) -COBOL_SUFFIXES = (".cbl", ".cob") -COPY_SUFFIXES = (".cpy", "") LINES, COLUMNS = 24, 80 @@ -310,10 +307,6 @@ def handled_keys(text: str, program: str) -> list[dict[str, Any]]: # ---- the whole snapshot ------------------------------------------------------------------------------------------------ -def _files(root: Path, suffixes: tuple[str, ...]) -> list[Path]: - return sorted(p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in suffixes) - - def code_only(text: str) -> str: """A fixed-format COBOL source with its comment lines (* or / in column 7) blanked.""" return "\n".join("" if len(line) > 6 and line[6] in "*/" else line for line in text.splitlines()) @@ -326,13 +319,14 @@ def _copies(text: str) -> set[str]: def inventory(legacy: Path) -> dict[str, Any]: """Every map in the snapshot with its fields, problems and function keys; the programs that use each mapset.""" rel = lambda p: p.relative_to(legacy).as_posix() # noqa: E731 - symbolic = {p.stem.upper(): p for p in _files(legacy, (".cpy",)) if "bms" in p.parent.name.lower()} + from reframe.source import kinds + symbolic = {p.stem.upper(): p for p in kinds.copybooks(legacy) if "bms" in p.parent.name.lower()} programs = {} - for p in _files(legacy, COBOL_SUFFIXES): + for p in kinds.files(legacy, "cobol"): text = p.read_text(errors="replace") programs[p.stem.upper()] = {"file": rel(p), "copies": _copies(text), "text": text} screens: list[dict[str, Any]] = [] - for p in _files(legacy, BMS_SUFFIXES): + for p in kinds.files(legacy, "bms"): for m in read_bms(p.read_text(errors="replace"), rel(p)): copybook = symbolic.get(m.mapset.upper()) users = sorted(name for name, prog in programs.items() if m.mapset.upper() in prog["copies"]) diff --git a/src/reframe/reconcile/inputs.py b/src/reframe/reconcile/inputs.py index 702290ed..9e78910c 100644 --- a/src/reframe/reconcile/inputs.py +++ b/src/reframe/reconcile/inputs.py @@ -22,7 +22,6 @@ from reframe.core.errors import Outcome, Stop from reframe.core.runfolder import RunFolder, iso -SOURCE_SUFFIXES = (".cbl", ".cob", ".jcl", ".cpy", ".bms", ".prc", ".proc", ".asm", ".pli", ".ctl") TEXT, PDF, WORD = (".md", ".markdown", ".txt"), (".pdf",), (".docx",) MARKS = {"Agree": "agree", "Needs change": "change", "Question": "question"} @@ -64,10 +63,12 @@ def preflight(folder: RunFolder, context: Path | None, auth: str = "subscription # ---- R1: the rules and their source citations ------------------------------------------------------------------------- def source_files(legacy: Path) -> dict[str, list[str]]: - """Program name -> the snapshot's source files with that stem, relative to the snapshot.""" + """Program name -> the snapshot's source files with that stem, relative to the snapshot: every kind of mainframe + source in Reframe's table (reframe.source.kinds), by extension or, for a member with none, by its content.""" + from reframe.source import kinds found: dict[str, list[str]] = defaultdict(list) for f in sorted(legacy.rglob("*")): - if f.is_file() and f.suffix.lower() in SOURCE_SUFFIXES: + if f.is_file() and kinds.is_source(f): found[f.stem.upper()].append(f.relative_to(legacy).as_posix()) return found diff --git a/src/reframe/source/kinds.py b/src/reframe/source/kinds.py new file mode 100644 index 00000000..20d30c45 --- /dev/null +++ b/src/reframe/source/kinds.py @@ -0,0 +1,169 @@ +"""What each file in a mainframe snapshot is (MP-01), in one table every reader uses. + +The extensions are AWS Transform's, from its user guide's list of mainframe source file types (the page on preparing +mainframe source artifacts, read 28 November 2026). AWS Transform classifies a file by its extension, and classes a file +with no extension, or `.txt`, by itself. Reframe does the same: a known extension decides, in any case (`.CBL` is +`.cbl`), and a file with no extension or `.txt` is classed by its content. Another extension the table does not name +(`.md`, `.java`, `.j2`) is not mainframe source; the package check (MP-03) says what such a file looks like. + +| Kind | AWS Transform's name | Extensions | Content that shows it, when the extension does not | +|----------------|---------------------------------|------------------------|-----------------------------------------------------| +| `cobol` | COBOL | .cbl .cob .cobol | an IDENTIFICATION (or ID) DIVISION | +| `copybook` | Copybooks | .cpy | COBOL data entries (level numbers) and no division | +| `bms` | BMS | .bms | a DFHMSD macro | +| `jcl` | JCL | .jcl | a `//name JOB` statement | +| `proc` | JCL Proc | .prc .proc | a `//name PROC` statement and no JOB | +| `include` | JCL Includes | .inc | – | +| `csd` | CICS Definition | .csd | DEFINE TRANSACTION, PROGRAM, MAPSET or FILE | +| `assembler` | Assembler | .asm | a CSECT, DSECT or START statement | +| `macro` | Macros | .mac | – | +| `pli` | PL/I | .pl1 (.pli, Reframe's) | a PROC with OPTIONS(MAIN), or PROC ... END | +| `pli-copybook` | PL/I copybooks | .pl1_copy | – | +| `rexx` | REXX | .rex .rexx | a first comment naming REXX | +| `easytrieve` | Easytrieve | .ezt | – | +| `natural` | Natural | .nat | – | +| `dclgen` | Db2 DCLGEN | .dcl | EXEC SQL DECLARE ... TABLE | +| `ddl` | Db2 definition | .sql .ddl | CREATE TABLE, INDEX, VIEW or TABLESPACE | +| `ims-stage1` | IMS definition (IMS Stage 1) | .ims | APPLCTN or TRANSACT macros | +| `dbd` | DBD | .dbd | a DBD macro with NAME= | +| `psb` | PSB | .psb | a PSBGEN macro, or PCB TYPE= | +| `mfs` | MFS | .mfs | – | +| `control-card` | Control Cards | .ctl | – | +| `ca7` | CA-7 job reports (LJOB) | .ca7 | – | +| `catalog` | catalog information (LISTCAT) | – | an IDCAMS listing of LISTCAT | + +`.pli` is not in AWS Transform's table; Reframe has read it as PL/I since pipeline 3, so it stays. The CICS resource-builder +YAML some codebases keep their CICS definitions in is read by the design's flow (MP-02); it is not a kind here, since +AWS Transform's table does not name it. +""" + +from __future__ import annotations + +import re +from functools import lru_cache +from pathlib import Path + +EXTENSIONS: dict[str, str] = { + ".cbl": "cobol", ".cob": "cobol", ".cobol": "cobol", ".cpy": "copybook", ".bms": "bms", ".jcl": "jcl", ".prc": "proc", + ".proc": "proc", ".inc": "include", ".csd": "csd", ".asm": "assembler", ".mac": "macro", ".pl1": "pli", ".pli": "pli", + ".pl1_copy": "pli-copybook", ".rex": "rexx", ".rexx": "rexx", ".ezt": "easytrieve", ".nat": "natural", ".dcl": "dclgen", + ".sql": "ddl", ".ddl": "ddl", ".ims": "ims-stage1", ".dbd": "dbd", ".psb": "psb", ".mfs": "mfs", ".ctl": "control-card", + ".ca7": "ca7", +} +"""Extension -> kind: AWS Transform's table, and `.pli`.""" + +AWS_NAMES: dict[str, str] = { + "cobol": "COBOL", "copybook": "Copybook", "bms": "BMS", "jcl": "JCL", "proc": "JCL Proc", "include": "JCL Include", + "csd": "CICS Definition", "assembler": "Assembler", "macro": "Macro", "pli": "PL/I", "pli-copybook": "PL/I copybook", + "rexx": "REXX", "easytrieve": "Easytrieve", "natural": "Natural", "dclgen": "Db2 DCLGEN", "ddl": "Db2 definition", + "ims-stage1": "IMS definition (Stage 1)", "dbd": "IMS DBD", "psb": "IMS PSB", "mfs": "IMS MFS", "control-card": "Control Card", + "ca7": "CA-7 report", "catalog": "catalog listing (LISTCAT)", +} + +AWS_EXTENSIONS = frozenset(EXTENSIONS) - {".pli"} +"""The extensions AWS Transform's table names.""" + +BY_CONTENT = frozenset({"", ".txt"}) +HEAD = 65536 # bytes read to class a file by its content + + +def _code(line: str) -> str: + """A fixed-format line's code: columns 8 to 72 when the sequence area is there, with comment lines dropped.""" + if len(line) > 6 and line[6] in "*/" and (line[:6].strip() == "" or line[:6].isdigit()): + return "" + return line + + +def content_kind(text: str) -> str | None: + """The kind a file's content shows, or None. Read from the first lines that are not comments.""" + upper = text.upper() + lines = [line for line in upper.splitlines() if line.strip()] + code = "\n".join(_code(line) for line in lines) + first = next((line for line in lines if not line.lstrip().startswith(("*", "//*"))), "") + if "IDCAMS" in upper and "LISTCAT" in upper: + return "catalog" + if re.search(r"^//\S*\s+JOB\b", code, re.M): + return "jcl" + if re.search(r"^//\S*\s+PROC\b", code, re.M): + return "proc" + if re.search(r"\b(IDENTIFICATION|ID)\s+DIVISION\b", code): + return "cobol" + if re.search(r"^\S*\s+DFHMSD\b", code, re.M): + return "bms" + if re.search(r"^\s*DEFINE\s+(TRANSACTION|PROGRAM|MAPSET|FILE)\s*\(", code, re.M): + return "csd" + if re.search(r"^\S*\s+DBD\s+.*\bNAME=", code, re.M): + return "dbd" + if re.search(r"^\S*\s+PSBGEN\b", code, re.M) or re.search(r"^\S*\s+PCB\s+TYPE=", code, re.M): + return "psb" + if re.search(r"^\S*\s+(APPLCTN|TRANSACT)\b", code, re.M): + return "ims-stage1" + if first.lstrip().startswith("/*") and "REXX" in first: + return "rexx" + if re.search(r"\bEXEC\s+SQL\s+DECLARE\s+\S+\s+TABLE\b", code): + return "dclgen" + if re.search(r"^\s*CREATE\s+(TABLE|INDEX|UNIQUE\s+INDEX|VIEW|TABLESPACE)\b", code, re.M): + return "ddl" + if re.search(r"\bPROC\s+OPTIONS\s*\(\s*MAIN\b", code) or (re.search(r":\s*PROC(EDURE)?\b", code) and re.search(r"\bEND\b", code)): + return "pli" + if re.search(r"^\S*\s+(CSECT|DSECT|START)\b", code, re.M): + return "assembler" + entries = [line for line in code.splitlines() if line.strip()] + data = sum(1 for line in entries if re.match(r"^.{0,11}\b(0?[1-9]|[1-4][0-9]|66|77|88)\s+[A-Z0-9][A-Z0-9-]*\b", line)) + if entries and data >= max(1, len(entries) // 2) and re.search(r"\b(PIC|PICTURE|REDEFINES|OCCURS|VALUE)\b", code): + return "copybook" + return None + + +def read_head(path: Path) -> bytes: + with path.open("rb") as handle: + return handle.read(HEAD) + + +def classify(name: str, head: bytes) -> str | None: + """The kind of a file from its name and its first bytes: its extension when the table names it, its content when it + has no extension or `.txt`, and nothing for another extension or a file that is not text.""" + suffix = Path(name).suffix.lower() + if suffix not in BY_CONTENT: + return EXTENSIONS.get(suffix) + if b"\x00" in head: + return None + return content_kind(head.decode("utf-8", errors="replace")) + + +@lru_cache(maxsize=65536) +def _kind_cached(path: str, size: int, mtime: float) -> str | None: + p = Path(path) + if p.suffix.lower() not in BY_CONTENT: + return EXTENSIONS.get(p.suffix.lower()) + try: + return classify(p.name, read_head(p)) + except OSError: + return None + + +def kind_of(path: Path) -> str | None: + """The kind of one file: its extension when the table names it, its content when it has no extension or `.txt`.""" + try: + stat = path.stat() + except OSError: + return None + return _kind_cached(str(path), stat.st_size, stat.st_mtime) + + +def files(root: Path, *kinds: str) -> list[Path]: + """Every file under root of one of the kinds, in name order.""" + wanted = set(kinds) + return sorted(p for p in root.rglob("*") if p.is_file() and kind_of(p) in wanted) + + +def is_source(path: Path) -> bool: + """A file Reframe reads as mainframe source: any kind but the system extracts (catalog listings and CA-7 reports).""" + return kind_of(path) not in (None, "catalog", "ca7") + + +def copybooks(root: Path) -> list[Path]: + """Every COBOL copybook, by its extension or its content, and as before the files with no extension in a folder whose + name starts with `cpy` that show nothing else (CardDemo keeps some copybooks that way).""" + return sorted(p for p in root.rglob("*") if p.is_file() and ( + kind_of(p) == "copybook" or (p.suffix == "" and kind_of(p) is None and p.parent.name.lower().startswith("cpy")))) diff --git a/tests/source/test_kinds.py b/tests/source/test_kinds.py new file mode 100644 index 00000000..2c17933c --- /dev/null +++ b/tests/source/test_kinds.py @@ -0,0 +1,102 @@ +"""MP-01: one table of source kinds, by extension or, for a member with none, by content; and the design and the +reconciliation reading a package laid out as AWS Transform documents it as they read the usual layout.""" +import tempfile +import unittest +from pathlib import Path + +from reframe.design import contracts, flow, inventory +from reframe.reconcile import inputs +from reframe.source import kinds +from tests.design.test_flow import ACCOUNT, CSD, MENU, MENU_TABLE, SIGNON, bms, cobol + +JCL = "//BUILDJOB JOB (ACCT),'BUILD',CLASS=A\n//STEP1 EXEC PGM=IEFBR14\n" +PROC = "//BUILD PROC\n//STEP1 EXEC PGM=IEBGENER\n// PEND\n" +DBD = " DBD NAME=ACCOUNT,ACCESS=(HIDAM,OSAM)\n SEGM NAME=ACCOUNT,BYTES=100\n DBDGEN\n FINISH\n END\n" +PSB = " PCB TYPE=DB,DBDNAME=ACCOUNT,PROCOPT=A,KEYLEN=10\n PSBGEN LANG=COBOL,PSBNAME=IBACSUM\n END\n" +STAGE1 = " APPLCTN PSB=IBACSUM,PGMTYPE=TP\n TRANSACT CODE=IBSUM,MSGTYPE=(SNGLSEG,RESPONSE)\n" +DDL = "CREATE TABLE ACCOUNT\n (ACCOUNT_ID CHAR(10) NOT NULL,\n BALANCE DECIMAL(12,2));\n" +DCLGEN = cobol("EXEC SQL DECLARE ACCOUNT TABLE", "( ACCOUNT_ID CHAR(10) NOT NULL )", "END-EXEC.", "01 DCLACCOUNT.", " 10 ACCOUNT-ID PIC X(10).") +LISTCAT = "1IDCAMS SYSTEM SERVICES TIME: 10:00:00\n0 LISTCAT ENT('AWS.M2.*') ALL\n" +REXX = "/* REXX */\nsay 'hello'\n" +PLI = "HELLO: PROC OPTIONS(MAIN);\n PUT LIST('HELLO');\nEND HELLO;\n" + + +class TableTest(unittest.TestCase): + def test_extensions_in_any_case(self): + for name, kind in [("A.cbl", "cobol"), ("A.CBL", "cobol"), ("A.cob", "cobol"), ("A.cobol", "cobol"), ("A.cpy", "copybook"), + ("A.BMS", "bms"), ("A.jcl", "jcl"), ("A.prc", "proc"), ("A.PROC", "proc"), ("A.csd", "csd"), ("A.pl1", "pli"), + ("A.pli", "pli"), ("A.pl1_copy", "pli-copybook"), ("A.dbd", "dbd"), ("A.psb", "psb"), ("A.ims", "ims-stage1"), + ("A.sql", "ddl"), ("A.ddl", "ddl"), ("A.dcl", "dclgen"), ("A.ca7", "ca7"), ("A.rexx", "rexx"), ("A.ctl", "control-card")]: + self.assertEqual(kinds.classify(name, b""), kind, name) + + def test_another_extension_is_not_classed_by_content(self): + self.assertIsNone(kinds.classify("deploy/build.jcl.j2", JCL.encode())) # a template: the package check reports it + self.assertIsNone(kinds.classify("README.md", cobol("IDENTIFICATION DIVISION.").encode())) + + def test_content_of_a_member_with_no_extension_or_txt(self): + cases = [(SIGNON, "cobol"), (MENU_TABLE, "copybook"), (bms("M", "MA", "F3=Exit"), "bms"), (CSD, "csd"), (JCL, "jcl"), + (PROC, "proc"), (DBD, "dbd"), (PSB, "psb"), (STAGE1, "ims-stage1"), (DDL, "ddl"), (DCLGEN, "dclgen"), + (LISTCAT, "catalog"), (REXX, "rexx"), (PLI, "pli")] + for text, kind in cases: + self.assertEqual(kinds.classify("MEMBER", text.encode()), kind, kind) + self.assertEqual(kinds.classify("MEMBER.txt", text.encode()), kind, kind) + + def test_what_shows_nothing_is_nothing(self): + self.assertIsNone(kinds.classify("LICENSE", b"Apache License\nVersion 2.0, January 2004\n\n1. Definitions.\n")) + self.assertIsNone(kinds.classify("NOTES.txt", b"1 apple\n2 pears\n")) # numbered lines, no PIC or VALUE + self.assertIsNone(kinds.classify("DATA", b"\x00\x01\x02binary")) + + +class AwsLayoutTest(unittest.TestCase): + """The same programs, copybooks, maps and transactions from the usual layout and from AWS Transform's package layout, + with upper-case extensions, members with no extension and `.txt`.""" + + USUAL = {"app/bms/SIGN00.bms": bms("SIGN00", "SIGN0A", "ENTER=Sign-on F3=Exit"), "app/bms/MENU00.bms": bms("MENU00", "MENU0A", "ENTER=Go F3=Exit"), + "app/bms/ACCTV00.bms": bms("ACCTV00", "ACCTV0A", "F3=Back F7=Up"), "app/cpy/MENU02Y.cpy": MENU_TABLE, + "app/cbl/SIGN00C.cbl": SIGNON, "app/cbl/MENU00C.cbl": MENU, "app/cbl/ACCTV00C.cbl": ACCOUNT, "app/csd/DEMO.csd": CSD} + AWS = {"bms/SIGN00.BMS": USUAL["app/bms/SIGN00.bms"], "bms/MENU00": USUAL["app/bms/MENU00.bms"], "bms/ACCTV00.txt": USUAL["app/bms/ACCTV00.bms"], + "copybooks/MENU02Y": MENU_TABLE, "cobol/SIGN00C": SIGNON, "cobol/MENU00C.txt": MENU, "cobol/ACCTV00C.CBL": ACCOUNT, + "cics/DEMO": CSD, "jcl/BUILDJOB": JCL} + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.usual, self.aws = Path(self.tmp.name) / "usual", Path(self.tmp.name) / "aws" + for root, files in ((self.usual, self.USUAL), (self.aws, self.AWS)): + for name, text in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(text) + + def read(self, legacy): + screens = inventory.inventory(legacy) + found = flow.flow(legacy, screens) + return {"programs": sorted(contracts.programs(legacy)), "copybooks": sorted(contracts.copybooks(legacy)), + "flow copybooks": sorted(flow._copybooks(legacy)), + "maps": sorted((s["mapset"], s["map"], tuple(p["name"] for p in s["programs"])) for s in screens["screens"]), + "transactions": sorted((t["transaction"], t["program"]) for t in flow.transactions(legacy)), + "links": sorted({(x["kind"], x["from"], x["to"]) for x in found["links"]}), + "keys": sorted((k["screen"], k["key"], tuple(sorted(k["to"]))) for k in found["keys"]), "unresolved": found["unresolved"]} + + def test_the_same_reading(self): + usual, aws = self.read(self.usual), self.read(self.aws) + self.assertEqual(usual["programs"], ["ACCTV00C", "MENU00C", "SIGN00C"]) + self.assertEqual(usual["transactions"], [("MN00", "MENU00C"), ("SG00", "SIGN00C")]) + self.assertIn(("xctl", "MENU00C", "ACCTV00C"), usual["links"]) # the menu table, read through the copybook + self.assertEqual(aws, usual) + + def test_the_reconciliation_reads_the_same_source(self): + usual, aws = inputs.source_files(self.usual), inputs.source_files(self.aws) + self.assertEqual(sorted(aws.keys() - {"BUILDJOB"}), sorted(usual)) + self.assertEqual(aws["SIGN00C"], ["cobol/SIGN00C"]) + self.assertEqual(aws["BUILDJOB"], ["jcl/BUILDJOB"]) + + def test_copybooks_outside_a_cpy_folder(self): + """Bank-of-Z keeps them in `copy/`; the flow followed COPY only into folders named cpy before MP-01.""" + root = Path(self.tmp.name) / "copy-folder" + (root / "src/cics/copy").mkdir(parents=True) + (root / "src/cics/copy/MENU02Y.cpy").write_text(MENU_TABLE) + self.assertEqual(list(flow._copybooks(root)), ["MENU02Y"]) + + +if __name__ == "__main__": + unittest.main() From 2fb55c66172081deb4ff1016655def618d20b829 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 07:48:29 -0700 Subject: [PATCH 02/13] MP-02: CICS definitions in either form The design's flow reads each transaction and its program from either form a codebase keeps its CICS definitions in, each citing its line: - DFHCSDUP's DEFINE statements, now with names that use the national characters `$`, `#` and `@` and spaces inside the brackets. Before, such a transaction was skipped. - IBM's CICS resource-builder YAML: a top-level `resourceDefinitions` list whose `transaction` entries name their `program`, as Bank-of-Z keeps its definitions. Any other YAML, or YAML that does not parse, gives nothing. On Bank-of-Z this reads 35 transactions: 14 of its own and 21 for IBM's debugger and TCP/IP listener. Tests: national characters in a CSD, a resource-builder file beside other YAML and a broken file, and YAML transactions reaching their programs in the flow with every cited line checked. Prepared with AI assistance. --- src/reframe/design/flow.py | 45 ++++++++++++++++++++++++++-- tests/design/test_flow.py | 60 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 3 deletions(-) diff --git a/src/reframe/design/flow.py b/src/reframe/design/flow.py index 063e71ef..07ca1858 100644 --- a/src/reframe/design/flow.py +++ b/src/reframe/design/flow.py @@ -2,7 +2,8 @@ Read from the source with no model, each link citing its lines: -- transaction to program, from the CSD (DEFINE TRANSACTION ... PROGRAM); +- transaction to program, from the CSD (DEFINE TRANSACTION ... PROGRAM, as DFHCSDUP writes it) or from IBM's CICS + resource-builder YAML (`resourceDefinitions`, each `transaction` naming its `program`) (MP-02); - program to program, from EXEC CICS XCTL and LINK, and RETURN TRANSID to another transaction; - a target held in a variable is resolved from the program's MOVEs into it and the VALUE clauses of the program and the copybooks it copies; a target taken from a table, such as a menu's option table, is resolved to every program in the @@ -235,16 +236,54 @@ def resolve(program: Program, expr: str, depth: int = 0) -> list[dict[str, Any]] # ---- the flow ---------------------------------------------------------------------------------------------------------- +CICS_NAME = r"([A-Za-z0-9$#@][^\s()]{0,7})" # a CICS resource name: letters, digits and the national characters $ # @, up to 8 + + def transactions(legacy: Path) -> list[dict[str, Any]]: + """Every transaction with its program, each citing the line that defines it: from the CSD's DEFINE statements and from + IBM's CICS resource-builder YAML. A transaction defined twice keeps every definition; the flow uses the first.""" from reframe.source import kinds found = [] for path in kinds.files(legacy, "csd"): text = path.read_text(errors="replace") - for m in re.finditer(r"DEFINE\s+TRANSACTION\((\w+)\)(.*?)(?=\bDEFINE\b|\Z)", text, re.S | re.I): - program = re.search(r"\bPROGRAM\((\w+)\)", m.group(2), re.I) + for m in re.finditer(r"DEFINE\s+TRANSACTION\(\s*" + CICS_NAME + r"\s*\)(.*?)(?=\bDEFINE\b|\Z)", text, re.S | re.I): + program = re.search(r"\bPROGRAM\(\s*" + CICS_NAME + r"\s*\)", m.group(2), re.I) if program: found.append({"transaction": m.group(1).upper(), "program": program.group(1).upper(), "lines": [f"{path.relative_to(legacy).as_posix()}:{text[:m.start()].count(chr(10)) + 1}"]}) + for path in sorted(p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() in (".yaml", ".yml")): + found += resource_builder(path, legacy) + return found + + +def resource_builder(path: Path, legacy: Path) -> list[dict[str, Any]]: + """The transactions in one file of IBM's CICS resource-builder YAML: a top-level `resourceDefinitions` list whose items + are `transaction:` mappings with a `name` and a `program`. Any other YAML gives nothing.""" + import yaml + text = path.read_text(errors="replace") + if "resourceDefinitions" not in text: + return [] + try: + root = yaml.compose(text, Loader=yaml.SafeLoader) + except yaml.YAMLError: + return [] + if not isinstance(root, yaml.MappingNode): + return [] + found = [] + for key, value in root.value: + if key.value != "resourceDefinitions" or not isinstance(value, yaml.SequenceNode): + continue + for item in value.value: + if not isinstance(item, yaml.MappingNode): + continue + for kind, body in item.value: + if kind.value != "transaction" or not isinstance(body, yaml.MappingNode): + continue + fields = {k.value: v.value for k, v in body.value if isinstance(v, yaml.ScalarNode)} + name, program = str(fields.get("name") or ""), str(fields.get("program") or "") + if re.fullmatch(CICS_NAME, name) and re.fullmatch(CICS_NAME, program): + found.append({"transaction": name.upper(), "program": program.upper(), + "lines": [f"{path.relative_to(legacy).as_posix()}:{kind.start_mark.line + 1}"]}) return found diff --git a/tests/design/test_flow.py b/tests/design/test_flow.py index d06491fa..0c773961 100644 --- a/tests/design/test_flow.py +++ b/tests/design/test_flow.py @@ -148,5 +148,65 @@ def test_branch_ends_at_the_closing_when(self): self.assertIn("SPACES", " ".join(program.lines[first - 1:last])) +RESOURCE_BUILDER = """# yaml-language-server: $schema=./resource-schema.json + +resourceDefinitions: + - mapset: + name: SIGN00 + group: DEMOGRP + - transaction: + name: SG00 + group: DEMOGRP + description: Sign on + program: SIGN00C + - program: + name: SIGN00C + group: DEMOGRP + - transaction: + name: "C$#@" + group: DEMOGRP + program: MENU00C +""" + + +class CicsDefinitionsTest(unittest.TestCase): + """MP-02: transactions from DFHCSDUP's DEFINE statements, national characters included, and from IBM's CICS + resource-builder YAML, each citing its line.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def write(self, name, text): + (self.root / name).parent.mkdir(parents=True, exist_ok=True) + (self.root / name).write_text(text) + + def test_national_characters_in_the_csd(self): + self.write("cics/DEMO.csd", " DEFINE TRANSACTION(C$01) GROUP(DEMO)\n PROGRAM(#MENU@) TWASIZE(0)\n" + " DEFINE TRANSACTION( MN00 ) GROUP(DEMO) PROGRAM( MENU00C )\n") + self.assertEqual([(t["transaction"], t["program"], t["lines"]) for t in flow.transactions(self.root)], + [("C$01", "#MENU@", ["cics/DEMO.csd:1"]), ("MN00", "MENU00C", ["cics/DEMO.csd:3"])]) + + def test_resource_builder_yaml(self): + self.write(".setup/zconfig/demo-definitions.yaml", RESOURCE_BUILDER) + self.write(".setup/zconfig/region.yaml", "region:\n transaction: XX00\n") # other YAML gives nothing + self.write("broken.yaml", "resourceDefinitions: [unclosed\n") + found = flow.transactions(self.root) + self.assertEqual([(t["transaction"], t["program"], t["lines"]) for t in found], + [("SG00", "SIGN00C", [".setup/zconfig/demo-definitions.yaml:7"]), ("C$#@", "MENU00C", [".setup/zconfig/demo-definitions.yaml:15"])]) + lines = (self.root / ".setup/zconfig/demo-definitions.yaml").read_text().splitlines() + self.assertEqual(lines[6].strip(), "- transaction:") + + def test_yaml_transactions_reach_their_programs_in_the_flow(self): + self.write("cbl/SIGN00C.cbl", SIGNON) + self.write("cbl/MENU00C.cbl", MENU) + self.write("cpy/MENU02Y.cpy", MENU_TABLE) + self.write("defs.yml", RESOURCE_BUILDER) + found = flow.flow(self.root, inventory.inventory(self.root)) + self.assertEqual({(x["from"], x["to"]) for x in found["links"] if x["kind"] == "transaction"}, {("SG00", "SIGN00C"), ("C$#@", "MENU00C")}) + self.assertEqual(flow.check(found, self.root), []) # every cited line exists + + if __name__ == "__main__": unittest.main() From c8848dbfc129604dbb5ba601322481613a6bf8f2 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 07:48:29 -0700 Subject: [PATCH 03/13] MP-03: a package check before the upload After the snapshot, and before anything is uploaded, Reframe reads the snapshot's archive and writes package-check.json in the run folder. It changes nothing in the source. It lists: - the files whose extension AWS Transform's table does not name, by extension, and those that look like mainframe source all the same (JCL kept as a `.j2` template; PL/I as `.pli`, where AWS's table names `.pl1`); - the files whose content is not what their extension says, with what AWS Transform takes them as (IMS DBD and PSB macros kept as `.asm` are taken as Assembler); - the files that are not text (SMF data belongs in its own folder), and the source files' encodings (ASCII or UTF-8, EBCDIC, or another), with a note when they are not one; - which system extracts are present: a catalog listing, CICS definitions (a CSD extract or resource-builder YAML), IMS Stage 1 and CA-7 reports. `reframe status` shows its line and notes, and both business reviews show it at the foot of the overview, beside the source's SHA-256. The snapshot's event log records `package_checked`. On Bank-of-Z: 724 files, 173 mainframe source, 537 with extensions AWS Transform does not name (32 of them look like JCL), 17 IMS definitions kept as `.asm`, 19 not text, one encoding, CICS definitions as YAML and no other extracts. Prepared with AI assistance. --- src/reframe/core/commands/reading.py | 6 ++ src/reframe/report/build.py | 12 ++- src/reframe/report/template.html | 4 +- src/reframe/source/package_check.py | 156 +++++++++++++++++++++++++++ src/reframe/source/snapshot.py | 8 +- tests/source/test_package_check.py | 103 ++++++++++++++++++ 6 files changed, 285 insertions(+), 4 deletions(-) create mode 100644 src/reframe/source/package_check.py create mode 100644 tests/source/test_package_check.py diff --git a/src/reframe/core/commands/reading.py b/src/reframe/core/commands/reading.py index 26765f24..a75e9336 100644 --- a/src/reframe/core/commands/reading.py +++ b/src/reframe/core/commands/reading.py @@ -37,6 +37,12 @@ def status(args) -> int: ui.hint(f"{state.get('source')} · {state.get('mode')} mode" + (" · Claude only, no AWS" if alone else "") + (f" · worker running (process {pid})" if pid else "")) ui.state("Status", f"{state.get('status')} · stage {state.get('stage')}", STATUS_STYLE.get(str(state.get("status")), "bold yellow")) + from reframe.source import package_check + checked = folder.load(package_check.FILE) + if checked: + ui.state("Package check", package_check.summary(checked), "") + for note in checked.get("notes", [])[1:]: + ui.hint(note) if state.get("graph"): graph = state["graph"] ui.state("Neptune", "existing cluster " + graph["name"] if graph["kind"] == "existing" else "a new graph", "") diff --git a/src/reframe/report/build.py b/src/reframe/report/build.py index 9e105e89..b3111232 100644 --- a/src/reframe/report/build.py +++ b/src/reframe/report/build.py @@ -28,6 +28,13 @@ # ---- reading AWS's files ------------------------------------------------------------------------- +def _package(folder: RunFolder) -> dict[str, Any]: + """The package check's line and notes (MP-03), for the source line at the foot of the overview.""" + from reframe.source import package_check + checked = folder.load(package_check.FILE) + return {"summary": package_check.summary(checked), "notes": checked.get("notes", [])[1:]} if checked else {} + + def _yaml(path: Path) -> Any: try: return yaml.safe_load(path.read_text(errors="replace")) if path.exists() else None @@ -149,7 +156,8 @@ def collect(folder: RunFolder) -> dict[str, Any]: "run": folder.root.name, "project": state.get("project"), "source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"), - "sha256": snapshot.get("sha256"), "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source")}, + "sha256": snapshot.get("sha256"), "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), + "package": _package(folder)}, "started_at": state.get("started_at"), "retrieved_at": state.get("retrieved_at"), "graph": (state.get("graph") or {}).get("kind"), "domains": ranked, "functions": functions, "capabilities": capabilities, @@ -379,7 +387,7 @@ def collect_claude(folder: RunFolder) -> dict[str, Any]: return { "generated_at": iso(), "run": folder.root.name, "project": project, "tool": CLAUDE, "source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"), "sha256": snapshot.get("sha256"), - "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source")}, + "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), "package": _package(folder)}, "started_at": (folder.state.get("claude") or {}).get("started_at"), "retrieved_at": model.get("read_at"), "domains": domains, "functions": functions, "capabilities": capabilities, "requirements": requirements, "rules": rules, "questions": questions, "data_model": data_objects, "sections": sections, "classification": [], "unclassified": [], "issues": [], "decisions": decisions, diff --git a/src/reframe/report/template.html b/src/reframe/report/template.html index 5207c7d1..eded368b 100644 --- a/src/reframe/report/template.html +++ b/src/reframe/report/template.html @@ -265,7 +265,9 @@

Your review

const other = D.domains.filter(d => d.kind !== 'business'); if (other.length) h += '

Also assessed

' + other.map(domainCard).join('') + '
'; h += '

Source: ' + esc(D.source.name) + (D.source.commit ? ', commit ' + esc(String(D.source.commit).slice(0, 12)) : '') + - ', SHA-256 ' + esc(String(D.source.sha256 || '').slice(0, 16)) + '… · results retrieved ' + esc(D.retrieved_at || '') + ' · page built ' + esc(D.generated_at) + '

'; + ', SHA-256 ' + esc(String(D.source.sha256 || '').slice(0, 16)) + '… · results retrieved ' + esc(D.retrieved_at || '') + ' · page built ' + esc(D.generated_at) + '

' + + (D.source.package && D.source.package.summary ? '
Package check: ' + esc(D.source.package.summary) + '
    ' + + (D.source.package.notes || []).map(n => '
  • ' + esc(n) + '
  • ').join('') + '
' : ''); return h; } // Pipeline 3: risk per capability and function, and decision tables (docs/pipeline-3.md, section 8.9). diff --git a/src/reframe/source/package_check.py b/src/reframe/source/package_check.py new file mode 100644 index 00000000..0fb45167 --- /dev/null +++ b/src/reframe/source/package_check.py @@ -0,0 +1,156 @@ +"""The package check (MP-03): what AWS Transform will make of a snapshot, before anything is uploaded. + +It reads the snapshot's archive, changes nothing, and writes `package-check.json` in the run folder: + +- `kinds`: every file's kind in Reframe's table (reframe.source.kinds), by extension or, with none, by content; +- `unnamed`: files whose extension AWS Transform's table does not name, by extension, and those whose content looks like + mainframe source all the same (for example JCL kept as a template, `.j2`); +- `disagree`: files whose content is not what their extension says, with what AWS Transform takes them as (IMS DBD and + PSB macros kept as `.asm` are taken as Assembler); +- `binary`: files that are not text. AWS Transform reads source as text; SMF data belongs in its own folder; +- `encodings`: the encodings of the source files. AWS Transform asks for one encoding across the files it documents; +- `extracts`: the system extracts present: a catalog listing (LISTCAT), CICS definitions (a CSD extract, or IBM's + resource-builder YAML, which Reframe reads and AWS Transform's table does not name), IMS Stage 1 and CA-7 reports; +- `notes`: the findings in words, shown by `reframe status` and on the reports. +""" + +from __future__ import annotations + +import zipfile +from collections import Counter +from pathlib import Path, PurePosixPath +from typing import Any + +from reframe.source import kinds + +FILE = "package-check.json" +SAMPLE = 50 # files listed per finding; the counts are whole +SAME = [{"jcl", "proc", "include"}, {"copybook", "dclgen"}, {"assembler", "macro"}, {"pli", "pli-copybook"}] +EXTRACTS = {"catalog": "catalog listing (LISTCAT)", "cics": "CICS definitions (CSD extract or resource-builder YAML)", + "ims-stage1": "IMS Stage 1 definitions", "ca7": "CA-7 job reports"} +EBCDIC_TEXT = set(range(0x81, 0x8A)) | set(range(0x91, 0x9A)) | set(range(0xA2, 0xAA)) | set(range(0xC1, 0xCA)) | \ + set(range(0xD1, 0xDA)) | set(range(0xE2, 0xEA)) | set(range(0xF0, 0xFA)) | {0x40, 0x4B, 0x5C, 0x61, 0x6B, 0x7D, 0x7E} + + +def encoding(head: bytes) -> str: + """`ascii`, `utf-8`, `ebcdic`, `other` (text in another single-byte encoding) or `binary`.""" + if not head: + return "ascii" + if b"\x00" in head: + return "binary" + try: + head.decode("utf-8") + except UnicodeDecodeError as error: + if error.start < len(head) - 3: # not merely a character cut off at the end of what was read + if sum(b in EBCDIC_TEXT for b in head) / len(head) > 0.8 and sum(0x61 <= b <= 0x7A for b in head) / len(head) < 0.05: + return "ebcdic" + controls = sum(b < 0x09 or 0x0E <= b < 0x20 for b in head) + return "binary" if controls / len(head) > 0.1 else "other" + return "ascii" if max(head) < 0x80 else "utf-8" + + +def _same(a: str, b: str) -> bool: + return a == b or any(a in group and b in group for group in SAME) + + +def check_archive(archive: Path) -> dict[str, Any]: + with zipfile.ZipFile(archive) as z: + members = [(m.filename, z.open(m).read(kinds.HEAD)) for m in z.infolist() if not m.is_dir()] + return check_members(members) + + +def check_members(members: list[tuple[str, bytes]]) -> dict[str, Any]: + """The check of a list of (path in the snapshot, first bytes of the file).""" + kinds_found: Counter[str] = Counter() + unnamed: Counter[str] = Counter() + looks: list[dict[str, str]] = [] + disagree: list[dict[str, str]] = [] + binary: list[str] = [] + encodings: Counter[str] = Counter() + extracts: dict[str, list[str]] = {key: [] for key in EXTRACTS} + for name, head in sorted(members): + suffix = PurePosixPath(name).suffix.lower() + enc = encoding(head) + kind = kinds.classify(name, head) + text = head.decode("utf-8", errors="replace") if enc != "binary" else "" + shown = kinds.content_kind(text) if text else None + if enc == "binary": + binary.append(name) + if kind: + kinds_found[kind] += 1 + encodings[enc] += 1 + if suffix not in kinds.BY_CONTENT and suffix not in kinds.AWS_EXTENSIONS: + unnamed[suffix] += 1 + if shown: + looks.append({"file": name, "looks_like": kinds.AWS_NAMES[shown]}) + elif suffix in kinds.AWS_EXTENSIONS and kind and shown and not _same(kind, shown): + disagree.append({"file": name, "extension": kinds.AWS_NAMES[kind], "content": kinds.AWS_NAMES[shown], + "aws_takes_it_as": kinds.AWS_NAMES[kind]}) + if kind in ("catalog", "ims-stage1", "ca7"): + extracts[kind].append(name) + if kind == "csd" or (suffix in (".yaml", ".yml") and "resourceDefinitions" in text): + extracts["cics"].append(name) + found: dict[str, Any] = { + "files": len(members), "kinds": dict(kinds_found.most_common()), + "unnamed": {"count": sum(unnamed.values()), "extensions": dict(unnamed.most_common()), "looks_like_source": looks[:SAMPLE], + "looks_like_source_count": len(looks)}, + "disagree": disagree[:SAMPLE], "disagree_count": len(disagree), + "binary": binary[:SAMPLE], "binary_count": len(binary), + "encodings": dict(encodings.most_common()), + "extracts": {key: files[:SAMPLE] for key, files in extracts.items()}, + } + found["notes"] = notes(found) + return found + + +def notes(found: dict[str, Any]) -> list[str]: + said = [] + source = sum(found["kinds"].values()) + said.append(f"{found['files']} files, {source} of them mainframe source by AWS Transform's table of extensions or by their content.") + u = found["unnamed"] + if u["count"]: + top = ", ".join(f"{ext or '(none)'} {n}" for ext, n in list(u["extensions"].items())[:6]) + said.append(f"{u['count']} files have an extension AWS Transform's table does not name ({top}); it may leave them out." + + (f" {u['looks_like_source_count']} of them look like mainframe source all the same, for example " + f"{u['looks_like_source'][0]['file']} ({u['looks_like_source'][0]['looks_like']})." if u["looks_like_source_count"] else "")) + for ext, n in u["extensions"].items(): + if ext in kinds.EXTENSIONS: # Reframe reads it; AWS Transform's table names another extension for the same kind + kind = kinds.EXTENSIONS[ext] + named = sorted(e for e, k in kinds.EXTENSIONS.items() if k == kind and e in kinds.AWS_EXTENSIONS) + said.append(f"{n} {ext} files are {kinds.AWS_NAMES[kind]}: Reframe reads them, but AWS Transform's table names " + f"{' and '.join(named)}, so it may leave them out.") + if found["disagree_count"]: + first = found["disagree"][0] + said.append(f"{found['disagree_count']} files hold something other than their extension says, for example {first['file']}: " + f"{first['content']}, which AWS Transform takes as {first['aws_takes_it_as']}.") + if found["binary_count"]: + said.append(f"{found['binary_count']} files are not text. AWS Transform reads source as text; SMF data goes in its own " + "folder, not with the source.") + text = {k: v for k, v in found["encodings"].items() if k != "binary"} + families = {"utf-8" if k in ("ascii", "utf-8") else k for k in text} + if len(families) > 1: + said.append("The source files are not in one encoding (" + ", ".join(f"{k} {v}" for k, v in text.items()) + + "). AWS Transform asks for one; otherwise its documentation may have empty sections.") + present = [EXTRACTS[k] for k, v in found["extracts"].items() if v] + missing = [EXTRACTS[k] for k, v in found["extracts"].items() if not v] + if present: + said.append("System extracts present: " + ", ".join(present) + ".") + if missing: + said.append("Not present: " + ", ".join(missing) + ". They come from the running system; the guide says how.") + return said + + +def summary(found: dict[str, Any] | None) -> str: + """One line for `reframe status` and the reports.""" + if not found: + return "" + parts = [f"{found['files']} files, {sum(found['kinds'].values())} mainframe source"] + if found["unnamed"]["count"]: + parts.append(f"{found['unnamed']['count']} with extensions AWS Transform does not name") + if found["disagree_count"]: + parts.append(f"{found['disagree_count']} whose content and extension disagree") + if found["binary_count"]: + parts.append(f"{found['binary_count']} not text") + families = {"utf-8" if k in ("ascii", "utf-8") else k for k in found["encodings"] if k != "binary"} + parts.append("one encoding" if len(families) <= 1 else "mixed encodings") + return "; ".join(parts) diff --git a/src/reframe/source/snapshot.py b/src/reframe/source/snapshot.py index 1dd835ed..ef43e38d 100644 --- a/src/reframe/source/snapshot.py +++ b/src/reframe/source/snapshot.py @@ -8,7 +8,8 @@ | a GitHub (or other Git) URL | cloned into the run folder at --ref, then git archive of that commit | Every archive is checked the same way before it is used: it opens, has no absolute or ".." paths and no -links, and unpacks to at most 2 GB. +links, and unpacks to at most 2 GB. Then the package check (reframe.source.package_check, MP-03) records what AWS +Transform will make of it in package-check.json, before anything is uploaded. """ from __future__ import annotations @@ -139,6 +140,11 @@ def take(folder: RunFolder, source: str, ref: str | None, runner: Runner = run_s shutil.copyfile(Path(source).expanduser(), archive) archive.chmod(0o600) files = check_archive(archive) + from reframe.source import package_check + checked = package_check.check_archive(archive) # what AWS Transform will make of it (MP-03); the archive is not changed + folder.save(package_check.FILE, checked) + folder.event("package_checked", files=checked["files"], unnamed=checked["unnamed"]["count"], disagree=checked["disagree_count"], + binary=checked["binary_count"], encodings=",".join(checked["encodings"])) data = archive.read_bytes() record: dict[str, Any] = {"source": source, "ref": ref, "form": form, "commit": commit, "files": files, "sha256": sha256_hex(data), "bytes": len(data), "archive": "source/archive.zip"} diff --git a/tests/source/test_package_check.py b/tests/source/test_package_check.py new file mode 100644 index 00000000..ec8d1257 --- /dev/null +++ b/tests/source/test_package_check.py @@ -0,0 +1,103 @@ +"""MP-03: the package check, after the snapshot and before the upload: what AWS Transform will make of the files, +changing nothing.""" +import contextlib +import io +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from reframe.core import commands +from reframe.core.runfolder import RunFolder +from reframe.report import build +from reframe.source import package_check, snapshot +from tests.design.test_flow import CSD, MENU_TABLE, SIGNON +from tests.source.test_kinds import DBD, JCL, LISTCAT, PSB + +EBCDIC = " IDENTIFICATION DIVISION.".encode("cp037") + + +class CheckTest(unittest.TestCase): + def check(self, files): + return package_check.check_members([(name, data if isinstance(data, bytes) else data.encode()) for name, data in files.items()]) + + def test_a_package_laid_out_as_aws_documents_it(self): + found = self.check({"cobol/SIGN00C.cbl": SIGNON, "copybooks/MENU02Y.cpy": MENU_TABLE, "cics/DEMO.csd": CSD, "jcl/BUILD.jcl": JCL, + "catalog/LISTCAT.txt": LISTCAT, "ca7/JOBS.ca7": "1LJOB report\n", "ims/STAGE1.ims": " APPLCTN PSB=X\n"}) + self.assertEqual(found["unnamed"]["count"], 0) + self.assertEqual(found["disagree_count"], 0) + self.assertEqual(found["binary_count"], 0) + self.assertEqual({k: bool(v) for k, v in found["extracts"].items()}, {"catalog": True, "cics": True, "ims-stage1": True, "ca7": True}) + self.assertEqual(found["kinds"]["cobol"], 1) + self.assertNotIn("Not present", " ".join(found["notes"])) + + def test_what_bank_of_z_shows(self): + """The shapes found in IBM's Bank-of-Z: IMS DBDs and PSBs kept as .asm, JCL kept as Jinja templates, PL/I as .pli, + CICS definitions as resource-builder YAML, pictures, and no system extracts.""" + found = self.check({"src/ims/DBD/ACCOUNT.asm": DBD, "src/ims/PSB/IBACSUM.asm": PSB, ".setup/deploy/ims_acbgen.jcl.j2": JCL, + "src/batch/pli/BNKSTMTP.pli": "BNKSTMTP: PROC OPTIONS(MAIN);\nEND BNKSTMTP;\n", + ".setup/zconfig/defs.yaml": "resourceDefinitions:\n - transaction:\n name: OMEN\n program: BNKMENU\n", + "docs/logo.png": b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR", "src/cics/cobol/BNKMENU.cbl": SIGNON}) + self.assertEqual([(d["file"], d["content"], d["aws_takes_it_as"]) for d in found["disagree"]], + [("src/ims/DBD/ACCOUNT.asm", "IMS DBD", "Assembler"), ("src/ims/PSB/IBACSUM.asm", "IMS PSB", "Assembler")]) + self.assertEqual(found["unnamed"]["extensions"], {".j2": 1, ".pli": 1, ".yaml": 1, ".png": 1}) + self.assertEqual(found["unnamed"]["looks_like_source"], [{"file": ".setup/deploy/ims_acbgen.jcl.j2", "looks_like": "JCL"}, + {"file": "src/batch/pli/BNKSTMTP.pli", "looks_like": "PL/I"}]) + self.assertEqual(found["binary"], ["docs/logo.png"]) + self.assertEqual(found["extracts"]["cics"], [".setup/zconfig/defs.yaml"]) + notes = " ".join(found["notes"]) + self.assertIn("IMS DBD, which AWS Transform takes as Assembler", notes) + self.assertIn("1 .pli files are PL/I: Reframe reads them, but AWS Transform's table names .pl1", notes) + self.assertIn("SMF data goes in its own folder", notes) + self.assertIn("Not present: catalog listing (LISTCAT), IMS Stage 1 definitions, CA-7 job reports", notes) + self.assertEqual(package_check.summary(found), "7 files, 4 mainframe source; 4 with extensions AWS Transform does not name; " + "2 whose content and extension disagree; 1 not text; one encoding") + + def test_mixed_encodings(self): + self.assertEqual(package_check.encoding(EBCDIC), "ebcdic") + self.assertEqual(package_check.encoding("café".encode()), "utf-8") + self.assertEqual(package_check.encoding("café".encode("latin-1") + b" " * 10), "other") + self.assertEqual(package_check.encoding(b"\x00\x01"), "binary") + found = self.check({"cobol/A.cbl": SIGNON, "cobol/B.cbl": EBCDIC}) + self.assertEqual(found["encodings"], {"ascii": 1, "ebcdic": 1}) + self.assertIn("not in one encoding", " ".join(found["notes"])) + self.assertTrue(package_check.summary(found).endswith("mixed encodings")) + + def test_a_character_cut_off_at_the_end_of_what_was_read_is_still_utf8(self): + self.assertEqual(package_check.encoding(("a" * 10 + "é").encode()[:-1]), "utf-8") + + +class SnapshotRecordsItTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + root = Path(self.tmp.name) + self.source = root / "source" + (self.source / "ims").mkdir(parents=True) + (self.source / "ims/ACCOUNT.asm").write_text(DBD) + (self.source / "MENU00C.cbl").write_text(SIGNON) + self.folder = RunFolder(root / "run") + self.folder.update(project="demo", source=str(self.source), mode="autonomous", status="RUNNING", stage="snapshot") + + def test_the_snapshot_writes_the_check_and_leaves_the_archive_as_it_is(self): + before = sorted(p.read_bytes() for p in self.source.rglob("*") if p.is_file()) + record = snapshot.take(self.folder, str(self.source), None, runner=lambda argv, env, timeout, data: subprocess.CompletedProcess(argv, 1, "", "")) + checked = self.folder.load(package_check.FILE) + self.assertEqual(checked["disagree"][0]["file"], "ims/ACCOUNT.asm") + self.assertEqual(record["files"], 2) # the archive has both files, unchanged + self.assertEqual(sorted(p.read_bytes() for p in self.source.rglob("*") if p.is_file()), before) + events = [json.loads(line) for line in self.folder.path("events.jsonl").read_text().splitlines()] + self.assertIn("package_checked", [e["event"] for e in events]) + + out = io.StringIO() + with mock.patch.object(commands, "find_run", return_value=self.folder), contextlib.redirect_stdout(out): + commands.status(type("Args", (), {"run": None})()) + self.assertIn("Package check", out.getvalue()) + self.assertIn("which AWS Transform takes as Assembler", out.getvalue().replace("\n", " ")) + self.assertEqual(build._package(self.folder)["summary"], package_check.summary(checked)) + + +if __name__ == "__main__": + unittest.main() From 7cbcce627eb91bee5336076a66ab1554b4e36eb2 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 07:48:30 -0700 Subject: [PATCH 04/13] MP-04: bringing source from a mainframe The guide has a section on giving Reframe a mainframe's source as AWS Transform documents its source package, linked to AWS's page: - the folders by type, AWS Transform's extensions and one encoding; - the optional system extracts: LISTCAT, the DFHCSDUP extract (and the resource-builder YAML Reframe also reads), IMS Stage 1 and CA-7; - that SMF data goes in its own folder and Reframe does not run AWS's activity analysis; - what the package check reports, and what to do about it. The code layout row for src/reframe/source/ names the table of source kinds and the package check. Prepared with AI assistance. --- docs/guide.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/guide.md b/docs/guide.md index 0cd3b04b..4c06d2cd 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4,6 +4,7 @@ Everything about running Reframe, step by step. Start with [How to run Reframe]( - [The home screen](#the-home-screen) - [Run an assessment: the guided way](#run-an-assessment-the-guided-way) +- [Bringing source from a mainframe](#bringing-source-from-a-mainframe) - [Claude only, with no AWS](#claude-only-with-no-aws) - [If a run stops](#if-a-run-stops) - [Results](#results) @@ -142,6 +143,31 @@ By default each run creates its own Neptune Serverless graph in a private networ To use a Neptune cluster you already have, pass `--graph existing` to choose from a list, or `--graph `. With no `--graph`, interactive mode lists the clusters in the region and asks. Reframe uses an existing cluster as it is and never changes or deletes it. It offers one only if it meets every need: available with an instance, Serverless, engine 1.4.5.1 or later, IAM authentication, encryption, subnets in two availability zones with an S3 gateway endpoint, a security group pair, and a bulk-loader role that can read the run's source bucket. For each cluster it rejects, it says why. +## Bringing source from a mainframe + +A Git repository of the application, like CardDemo's, is the easiest source. Code taken from a mainframe usually comes as AWS Transform documents its source package, in [the AWS Transform user guide's page on mainframe source artifacts](https://docs.aws.amazon.com/transform/latest/userguide/transform-app-mainframe-source-artifacts.html). Reframe reads that package as it is: give `--source` the folder or the ZIP file. + +**The package.** +- Put one folder per artifact type, for example `cobol/`, `jcl/`, `copybooks/`, `db2/`, `ims/`, `cics/` and `ca7/`. The names are AWS's examples; Reframe does not need them. +- Use AWS Transform's extensions, in any case: `.cbl` (or `.cob`, `.cobol`), `.cpy`, `.bms`, `.jcl`, `.prc`, `.pl1`, `.asm`, `.csd`, `.dbd`, `.psb`, `.sql` and the others on AWS's page. A member downloaded with no extension, or as `.txt`, is classed by its content, as AWS Transform classes it. +- Keep every file in one encoding. Files transferred in text mode arrive in ASCII or UTF-8. AWS Transform asks for one encoding across the files, or its documentation can have empty sections. + +**The system extracts** come from the running system, not the source library. AWS's page gives the job for each. Each is optional, and Reframe reports which are there: +- the catalog listing, from IDCAMS `LISTCAT`; +- the CICS definitions, from `DFHCSDUP` `EXTRACT`, as a `.csd` file. The design's flow reads its `DEFINE TRANSACTION` statements, and also IBM's CICS resource-builder YAML (`resourceDefinitions`), where a codebase keeps its definitions that way; +- the IMS definitions, as IMS Stage 1 from `DFSURDD0`, `.ims`; +- the CA-7 job reports, from `LJOB`, `.ca7`. + +**SMF data** goes in its own folder in S3, not with the source. AWS Transform uses it for its activity analysis, which Reframe does not run, so leave it out of what you give `--source`. + +**The package check.** After the snapshot, and before anything is uploaded, Reframe writes `package-check.json` in the run folder. It changes nothing in the source. `reframe status` shows it, and the reviews show it at the foot of the overview. It lists: +- the files whose extension AWS Transform's table does not name, and those among them that look like mainframe source all the same, for example JCL kept as a template; +- the files whose content is not what their extension says, with what AWS Transform will take them as. IMS DBD and PSB macros kept as `.asm` are taken as Assembler; +- the files that are not text, and the encodings of the source files; +- which system extracts are present. + +Where the check finds something, fix the package and start a new run, or go ahead knowing what AWS Transform will leave out. + ## Claude only, with no AWS No AWS account, or no AWS Transform? Run Reframe with Claude only ([release 1.0](release-1.md), section 2). It needs Git, [Claude Code](https://docs.anthropic.com/en/docs/claude-code) signed in, and the code-modernization plugin, which Reframe fetches itself. Claude signs in with your Claude subscription (the default), an Anthropic API key (`--auth api-key`, with `ANTHROPIC_API_KEY` set), or Amazon Bedrock (`--auth bedrock --profile --region `, the profile used for Bedrock only, or `AWS_BEARER_TOKEN_BEDROCK`). @@ -423,7 +449,7 @@ This is optional too. It puts the cleaned copy on the repository's `gh-pages` br | Folder | What it does | |---|---| | `src/reframe/core/` | The CLI, the run folder and its change records, preflight, the stage pipeline and teardown | -| `src/reframe/source/` | Taking the source snapshot and uploading it to S3 | +| `src/reframe/source/` | Taking the source snapshot, the table of source kinds, the package check, and uploading the snapshot to S3 | | `src/reframe/infrastructure/` | The Terraform roots and modules, the Neptune cluster checks and the network clean-up | | `src/reframe/transform/` | AWS Transform: the MCP client, the workspace and connector, the job driver, answering questions, retrieval | | `src/reframe/claude/` | The Claude assessment: the pinned plugin, running Claude Code headless, the workspace, the plugin's steps, retrieval, the generated requirements and the graph load | From 75d5cb3465796cf630f6858c69e8ce0b6449bd6b Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 07:59:47 -0700 Subject: [PATCH 05/13] L1-01: the stack profile After the snapshot, with no model, Reframe works out what the codebase is and records it in stack-profile.json (docs/any-legacy.md, section 4): - languages, counted by file and by line: by extension, by content for the shared `.inc`, `.h` and `.prc`, and a mainframe member with no extension as reframe.source.kinds classes it; - the family that carries more than half the lines (mainframe, java, dotnet, web-script, front-end, native, 4gl, or mixed). SQL counts toward none, since every stack has a schema. JavaScript and TypeScript count toward front-end only when no other family has a quarter of the code. Libraries kept in the tree (node_modules, vendor, packages, minified files) are not counted; - what it has, each with the files that show it: user interface, routes, jobs and data; - the prompts' words: "COBOL" for the mainframe, as today, or the family's two main languages ("Java and JSP"). `reframe run --legacy ` overrides the family, and the profile records what was found and what it was told. For a local source, the guided run shows the profile before the run starts and asks only when no family carries most of the code. `reframe status` shows it, and both business reviews show it at the foot of the overview. The package check is now shown only for mainframe code, the only code AWS Transform reads. Tests: six synthetic fixtures written for the tests (a Java web application, .NET, PHP, a batch-only Java job, a mainframe and a mixed codebase) in tests/stacks.py. Each one's family, what it has with the files, the words, the skipped libraries, the shared extensions, the override, the snapshot's record, status and the reports. Bank-of-Z profiles as mainframe: COBOL carries 33.8k lines against about 3.8k of Java and JavaScript. Prepared with AI assistance. --- docs/cli.md | 1 + src/reframe/core/cli.py | 4 + src/reframe/core/commands/reading.py | 7 +- src/reframe/core/commands/starting.py | 15 +- src/reframe/core/guide.py | 25 ++- src/reframe/report/build.py | 18 +- src/reframe/report/template.html | 1 + src/reframe/source/profile.py | 206 +++++++++++++++++ src/reframe/source/snapshot.py | 7 +- tests/source/test_profile.py | 120 ++++++++++ tests/stacks.py | 309 ++++++++++++++++++++++++++ 11 files changed, 697 insertions(+), 16 deletions(-) create mode 100644 src/reframe/source/profile.py create mode 100644 tests/source/test_profile.py create mode 100644 tests/stacks.py diff --git a/docs/cli.md b/docs/cli.md index bdde6f59..89dab517 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -108,6 +108,7 @@ Assess mainframe source with AWS Transform and Claude, or with Claude only (--to | `--terraform ` | the Terraform binary to use (default: REFRAME_TERRAFORM, then the one Reframe installed, then terraform on PATH) | | `--foreground` | run in this terminal instead of a background worker | | `--tools both\|claude\|aws` | both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: AWS Transform only (reframe claude adds Claude later) | +| `--legacy mainframe\|java\|dotnet\|web-script\|front-end\|native\|4gl\|mixed` | the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, section 4); AWS Transform is offered only for mainframe | | `--max-agents ` | the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo) | | `--auth subscription\|api-key\|bedrock` | how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock (with --tools claude, --profile and --region are used for Bedrock only) | diff --git a/src/reframe/core/cli.py b/src/reframe/core/cli.py index afb4ba68..fac2d2a0 100644 --- a/src/reframe/core/cli.py +++ b/src/reframe/core/cli.py @@ -11,6 +11,7 @@ import sys from reframe import __version__ +from reframe.source.profile import FAMILIES # how Claude signs in; the same as reframe.claude.preflight.AUTHS, kept here so the CLI starts without loading it AUTHS = ("subscription", "api-key", "bedrock") @@ -66,6 +67,9 @@ def command(name: str, help: str) -> argparse.ArgumentParser: run.add_argument("--tools", choices=("both", "claude", "aws"), default="both", help="both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: " "AWS Transform only (reframe claude adds Claude later)") + run.add_argument("--legacy", choices=FAMILIES, default=None, + help="the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, " + "section 4); AWS Transform is offered only for mainframe") run.add_argument("--max-agents", type=int, help="the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo)") run.add_argument("--auth", choices=AUTHS, default=None, help="how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock " diff --git a/src/reframe/core/commands/reading.py b/src/reframe/core/commands/reading.py index a75e9336..368e4772 100644 --- a/src/reframe/core/commands/reading.py +++ b/src/reframe/core/commands/reading.py @@ -37,9 +37,12 @@ def status(args) -> int: ui.hint(f"{state.get('source')} · {state.get('mode')} mode" + (" · Claude only, no AWS" if alone else "") + (f" · worker running (process {pid})" if pid else "")) ui.state("Status", f"{state.get('status')} · stage {state.get('stage')}", STATUS_STYLE.get(str(state.get("status")), "bold yellow")) - from reframe.source import package_check + from reframe.source import package_check, profile + stack = folder.load(profile.FILE) + if stack: + ui.state("Stack", profile.summary(stack), "") checked = folder.load(package_check.FILE) - if checked: + if checked and (not stack or stack.get("family") == "mainframe"): # what AWS Transform makes of it: mainframe code only ui.state("Package check", package_check.summary(checked), "") for note in checked.get("notes", [])[1:]: ui.hint(note) diff --git a/src/reframe/core/commands/starting.py b/src/reframe/core/commands/starting.py index ef8b90e5..f21c62cc 100644 --- a/src/reframe/core/commands/starting.py +++ b/src/reframe/core/commands/starting.py @@ -20,7 +20,8 @@ def run(args) -> int: if getattr(args, "tools", "both") == "claude": return commands.start_claude_only(source=args.source, ref=args.ref, mode=args.mode, project=args.project, foreground=args.foreground, max_agents=getattr(args, "max_agents", None), auth=auth, - profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None) + profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None, + legacy=getattr(args, "legacy", None)) from reframe.core.setup import load_config saved = load_config() profile = args.profile or saved.get("profile") @@ -29,11 +30,11 @@ def run(args) -> int: both = getattr(args, "tools", "both") == "both" # the Claude assessment alongside, as the guided run offers by default return commands.start(source=args.source, profile=profile, ref=args.ref, mode=args.mode, region=args.region or saved.get("region") or "us-east-1", project=args.project, graph=args.graph, terraform=args.terraform, foreground=args.foreground, - claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None) + claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=getattr(args, "legacy", None)) def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, project: str | None, graph: str | None, - terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None) -> int: + terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None, legacy: str | None = None) -> int: """Stage 0 and the Neptune choice here, then stages 1 to 8 in a background worker (or this terminal).""" from reframe.core import pipeline, ui from reframe.source.snapshot import kind @@ -45,7 +46,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, except (Stop, ReframeError) as error: return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error))) folder.update(project=project, source=source, ref=ref, mode=mode, graph_arg=graph, profile=profile, - region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING") + region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING", + **({"legacy": legacy} if legacy else {})) ui.section(f"Run {folder.root.name}") ui.hint(f"{project} · {mode} mode · run folder {folder.root}") ctx = pipeline.Context.load(folder) @@ -75,7 +77,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, def start_claude_only(*, source: str, ref: str | None, mode: str, project: str | None, foreground: bool, - max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None) -> int: + max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None, + legacy: str | None = None) -> int: """A Claude-only run (docs/release-1.md, section 2): the snapshot and the Claude assessment, in one commands.worker, with no AWS resources. With Amazon Bedrock, the AWS profile (or a Bedrock API key) is used to sign Claude in, and for nothing else.""" from reframe.claude import pipeline as claude_pipeline @@ -89,7 +92,7 @@ def start_claude_only(*, source: str, ref: str | None, mode: str, project: str | except (Stop, ReframeError) as error: return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error))) folder.update(tools="claude", project=project, source=source, ref=ref, mode=mode, started_at=iso(), stage="snapshot", status="RUNNING", - **({"profile": profile, "region": region or "us-east-1"} if profile else {})) + **({"profile": profile, "region": region or "us-east-1"} if profile else {}), **({"legacy": legacy} if legacy else {})) claude_pipeline.request(pipeline.Context.load(folder), auth=auth, max_agents=max_agents, mode=mode) ui.section(f"Run {folder.root.name} · Claude only") signin = {"subscription": "your Claude subscription", "api-key": "your Anthropic API key", diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py index 0df87742..b7b979c8 100644 --- a/src/reframe/core/guide.py +++ b/src/reframe/core/guide.py @@ -211,6 +211,24 @@ def check_url(value: str) -> str | None: return str(Path(archive).expanduser().resolve()), None +def stack(chosen_source: str) -> str | None: + """The stack profile of a local source (L1-01), shown before the run starts; asked only when no family carries most of + the code. Returns the family the person chose, or None to keep what was found. A Git URL is profiled after the snapshot.""" + from reframe.source import profile + path = Path(chosen_source) + if not path.exists(): + ui.hint("The stack profile is worked out after the snapshot; reframe status shows it.") + return None + with ui.console.status("Working out the stack…"): + found = profile.profile_folder(path) if path.is_dir() else profile.profile_archive(path) + ui.state("Stack", profile.summary(found), "") + if found["found"] != "mixed": + return None + families = list(profile.FAMILIES) + picked = ui.choose("No family carries most of the code. Which is it?", [(f, "") for f in families], len(families)) + return None if families[picked - 1] == "mixed" else families[picked - 1] + + # ---- 4 and 5. choices, summary, start ---------------------------------------------------------------- @@ -355,13 +373,14 @@ def run(args) -> int: if picked_source is None: return 1 chosen, ref = picked_source + legacy = stack(chosen) picked = claude_only_choices(chosen) if not claude_only_summary(chosen, ref, picked): ui.hint("Nothing was started or created.") return 0 return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"], foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"], - auth=picked["claude"]["auth"]) + auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {})) if not prerequisites(m): return 1 sign = sign_in() @@ -371,6 +390,7 @@ def run(args) -> int: if picked_source is None: return 1 chosen, ref = picked_source + legacy = stack(chosen) picked = choices(chosen) if not summary(chosen, ref, sign, picked): ui.hint("Nothing was started or created.") @@ -380,7 +400,8 @@ def run(args) -> int: ui.hint("Stopped. Nothing was started or created.") return 130 return commands.start(source=chosen, profile=sign.profile, ref=ref, mode=picked["mode"], region=sign.region, project=picked["project"], - graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude")) + graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude"), + **({"legacy": legacy} if legacy else {})) def setup_only(args) -> int: diff --git a/src/reframe/report/build.py b/src/reframe/report/build.py index b3111232..e78f025b 100644 --- a/src/reframe/report/build.py +++ b/src/reframe/report/build.py @@ -28,11 +28,19 @@ # ---- reading AWS's files ------------------------------------------------------------------------- +def _stack(folder: RunFolder) -> str: + """The stack profile's line (L1-01), for the source line at the foot of the overview.""" + from reframe.source import profile + return profile.summary(folder.load(profile.FILE)) + + def _package(folder: RunFolder) -> dict[str, Any]: """The package check's line and notes (MP-03), for the source line at the foot of the overview.""" - from reframe.source import package_check - checked = folder.load(package_check.FILE) - return {"summary": package_check.summary(checked), "notes": checked.get("notes", [])[1:]} if checked else {} + from reframe.source import package_check, profile + checked, stack = folder.load(package_check.FILE), folder.load(profile.FILE) + if not checked or (stack and stack.get("family") != "mainframe"): # what AWS Transform makes of it: mainframe code only + return {} + return {"summary": package_check.summary(checked), "notes": checked.get("notes", [])[1:]} def _yaml(path: Path) -> Any: @@ -157,7 +165,7 @@ def collect(folder: RunFolder) -> dict[str, Any]: "project": state.get("project"), "source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"), "sha256": snapshot.get("sha256"), "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), - "package": _package(folder)}, + "package": _package(folder), "stack": _stack(folder)}, "started_at": state.get("started_at"), "retrieved_at": state.get("retrieved_at"), "graph": (state.get("graph") or {}).get("kind"), "domains": ranked, "functions": functions, "capabilities": capabilities, @@ -387,7 +395,7 @@ def collect_claude(folder: RunFolder) -> dict[str, Any]: return { "generated_at": iso(), "run": folder.root.name, "project": project, "tool": CLAUDE, "source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"), "sha256": snapshot.get("sha256"), - "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), "package": _package(folder)}, + "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), "package": _package(folder), "stack": _stack(folder)}, "started_at": (folder.state.get("claude") or {}).get("started_at"), "retrieved_at": model.get("read_at"), "domains": domains, "functions": functions, "capabilities": capabilities, "requirements": requirements, "rules": rules, "questions": questions, "data_model": data_objects, "sections": sections, "classification": [], "unclassified": [], "issues": [], "decisions": decisions, diff --git a/src/reframe/report/template.html b/src/reframe/report/template.html index eded368b..fb071504 100644 --- a/src/reframe/report/template.html +++ b/src/reframe/report/template.html @@ -266,6 +266,7 @@

Your review

if (other.length) h += '

Also assessed

' + other.map(domainCard).join('') + '
'; h += '

Source: ' + esc(D.source.name) + (D.source.commit ? ', commit ' + esc(String(D.source.commit).slice(0, 12)) : '') + ', SHA-256 ' + esc(String(D.source.sha256 || '').slice(0, 16)) + '… · results retrieved ' + esc(D.retrieved_at || '') + ' · page built ' + esc(D.generated_at) + '

' + + (D.source.stack ? '

Stack: ' + esc(D.source.stack) + '

' : '') + (D.source.package && D.source.package.summary ? '
Package check: ' + esc(D.source.package.summary) + '
    ' + (D.source.package.notes || []).map(n => '
  • ' + esc(n) + '
  • ').join('') + '
' : ''); return h; diff --git a/src/reframe/source/profile.py b/src/reframe/source/profile.py new file mode 100644 index 00000000..9203c703 --- /dev/null +++ b/src/reframe/source/profile.py @@ -0,0 +1,206 @@ +"""The stack profile (L1-01, docs/any-legacy.md section 4): what the codebase is, worked out after the snapshot with no +model, and recorded in `stack-profile.json` in the run folder. + +- **languages,** counted by file and by line: by extension, and by content where an extension is shared (`.inc`, `.h`, + `.prc`); a mainframe member with no extension is classed as `reframe.source.kinds` classes it; +- **family,** from the languages that carry most of the code (more than half its lines; SQL counts toward none, since + every stack has a schema). JavaScript and TypeScript count + toward `front-end` only when no other family has a quarter of the code: a web application's scripts belong to it. + Libraries kept in the tree (`node_modules`, `vendor`, `packages`, minified files) are not counted; +- **what it has,** each with the files that show it: user interface, routes, jobs and data; +- **words,** for the prompts: the languages' names and what an agent follows through the code. + +`reframe run --legacy ` overrides the family; the profile records both what was found and what was told. +""" + +from __future__ import annotations + +import re +import zipfile +from collections import Counter, defaultdict +from pathlib import Path, PurePosixPath +from typing import Any + +from reframe.source import kinds + +FILE = "stack-profile.json" +FAMILIES = ("mainframe", "java", "dotnet", "web-script", "front-end", "native", "4gl", "mixed") +SAMPLE = 50 +READ = 1 << 20 # bytes of each file searched for the patterns below + +MAINFRAME_LANGUAGES = {"cobol": "COBOL", "copybook": "COBOL", "dclgen": "COBOL", "bms": "BMS", "jcl": "JCL", "proc": "JCL", + "include": "JCL", "csd": "CICS CSD", "assembler": "HLASM", "macro": "HLASM", "pli": "PL/I", + "pli-copybook": "PL/I", "rexx": "REXX", "easytrieve": "Easytrieve", "ddl": "SQL", "ims-stage1": "IMS", + "dbd": "IMS", "psb": "IMS", "mfs": "IMS", "control-card": "JCL", "natural": "Natural"} +"""Reframe's mainframe kinds -> the language they are written in. Natural is a 4GL (section 4); the rest are mainframe.""" + +OTHER = { + ".java": ("Java", "java"), ".jsp": ("JSP", "java"), ".jspx": ("JSP", "java"), ".jsf": ("JSF", "java"), ".xhtml": ("JSF", "java"), + ".groovy": ("Groovy", "java"), ".kt": ("Kotlin", "java"), ".kts": ("Kotlin", "java"), + ".cs": ("C#", "dotnet"), ".vb": ("VB.NET", "dotnet"), ".aspx": ("ASP.NET", "dotnet"), ".ascx": ("ASP.NET", "dotnet"), + ".master": ("ASP.NET", "dotnet"), ".asax": ("ASP.NET", "dotnet"), ".ashx": ("ASP.NET", "dotnet"), ".cshtml": ("Razor", "dotnet"), + ".vbhtml": ("Razor", "dotnet"), ".razor": ("Razor", "dotnet"), + ".php": ("PHP", "web-script"), ".phtml": ("PHP", "web-script"), ".pl": ("Perl", "web-script"), ".pm": ("Perl", "web-script"), + ".cgi": ("Perl", "web-script"), ".rb": ("Ruby", "web-script"), ".erb": ("Ruby", "web-script"), ".py": ("Python", "web-script"), + ".asp": ("classic ASP", "web-script"), + ".js": ("JavaScript", "front-end"), ".jsx": ("JavaScript", "front-end"), ".mjs": ("JavaScript", "front-end"), + ".ts": ("TypeScript", "front-end"), ".tsx": ("TypeScript", "front-end"), ".vue": ("Vue", "front-end"), + ".c": ("C", "native"), ".cpp": ("C++", "native"), ".cc": ("C++", "native"), ".cxx": ("C++", "native"), ".hpp": ("C++", "native"), + ".rpg": ("RPG", "4gl"), ".rpgle": ("RPG", "4gl"), ".sqlrpgle": ("RPG", "4gl"), ".p": ("Progress 4GL", "4gl"), ".w": ("Progress 4GL", "4gl"), + ".srw": ("PowerBuilder", "4gl"), ".sru": ("PowerBuilder", "4gl"), ".srd": ("PowerBuilder", "4gl"), ".frm": ("VB6", "4gl"), + ".bas": ("VB6", "4gl"), ".cls": ("VB6", "4gl"), ".vbp": ("VB6", "4gl"), ".pas": ("Delphi", "4gl"), ".dfm": ("Delphi", "4gl"), + ".dpr": ("Delphi", "4gl"), ".fmb": ("Oracle Forms", "4gl"), ".fmt": ("Oracle Forms", "4gl"), +} +"""Extension -> (language, family) outside the mainframe table.""" + +SHARED = {".inc", ".h", ".prc"} # extensions more than one stack uses: classed by content +SKIPPED_FOLDERS = {"node_modules", "bower_components", "vendor", "packages", "third_party", "thirdparty", ".git", ".svn", ".idea", + ".vscode", "target", "bin", "obj", "dist", "build", ".gradle", "__pycache__"} + +LANGUAGE_FAMILY = {lang: family for lang, family in OTHER.values()} | {lang: "mainframe" for lang in MAINFRAME_LANGUAGES.values()} \ + | {"Natural": "4gl", "PHP": "web-script", "C": "native", "C++": "native", "JCL": "mainframe", "SQL": "data"} +"""Language -> family. SQL is `data`: every stack has a schema, so it counts toward no family.""" + +# what the codebase has: (pattern on the path, pattern on the content, or None), each shown by the files that match +UI = [(r"\.(bms|mfs|jsp|jspx|xhtml|jsf|aspx|ascx|master|cshtml|vbhtml|razor|erb|phtml|vue|frm|dfm|fmb|srw)$", None), + (r"(^|/)(templates|views|pages|WEB-INF/jsp)/.+\.html?$", None), + (r"\.php$", r"<(html|form|input|body)\b"), (r"\.(jsx|tsx)$", r"<[A-Z]?\w+[^>]*>")] +ROUTES = [(r"\.csd$", None), (r"\.ya?ml$", r"resourceDefinitions:"), (r"(^|/)web\.xml$", r""), + (r"(^|/)struts[\w-]*\.xml$", r"(get|post|map)\(|Route::(get|post)"), (r"\.(js|ts)$", r"\$routeProvider|\bcreateRouter\(| bool: + parts = PurePosixPath(name).parts + return any(p in SKIPPED_FOLDERS for p in parts[:-1]) or bool(re.search(r"\.min\.(js|css)$", name)) or parts[-1].startswith(".") + + +def language(name: str, head: bytes) -> str | None: + """The language of one file, or None for a file that is not code (documentation, data, configuration, pictures).""" + suffix = PurePosixPath(name).suffix.lower() + if suffix in OTHER: + return OTHER[suffix][0] + if suffix in SHARED: + text = head.decode("utf-8", errors="replace") + if suffix == ".h": + return "C" + if re.search(r"<\?php", text): + return "PHP" + if re.search(r"^\s*#\s*(include|define|ifndef)\b", text, re.M): + return "C" + if re.search(r"^//\S*\s+(EXEC|DD|PROC|PEND|SET|IF|INCLUDE)\b", text, re.M): + return "JCL" + return None + kind = kinds.classify(name, head) + return MAINFRAME_LANGUAGES.get(kind) if kind else None + + +def family_of(lines: dict[str, int]) -> str: + """The family that carries most of the code's lines. Front-end scripts count only when no other family has a quarter.""" + by_family: Counter[str] = Counter() + for lang, n in lines.items(): + if LANGUAGE_FAMILY.get(lang) != "data": + by_family[LANGUAGE_FAMILY.get(lang, "mixed")] += n + total = sum(by_family.values()) + if not total: + return "mixed" + servers = {f: n for f, n in by_family.items() if f != "front-end"} + if servers and max(servers.values()) >= total / 4: + top, n = max(servers.items(), key=lambda kv: kv[1]) + return top if n > sum(servers.values()) / 2 else "mixed" + top, n = by_family.most_common(1)[0] + return top if n > total / 2 else "mixed" + + +def _matches(rules: list[tuple[str, str | None]], name: str, text: str) -> bool: + for path_pattern, content_pattern in rules: + if re.search(path_pattern, name, re.I) and (content_pattern is None or re.search(content_pattern, text)): + return True + return False + + +def profile_members(members: list[tuple[str, bytes, int]], told: str | None = None) -> dict[str, Any]: + """The profile of a list of (path in the snapshot, the file's first bytes, its line count).""" + files: Counter[str] = Counter() + lines: Counter[str] = Counter() + has: dict[str, list[str]] = defaultdict(list) + skipped = 0 + for name, head, count in sorted(members): + if _skipped(name): + skipped += 1 + continue + lang = language(name, head) + text = head.decode("utf-8", errors="replace") + if lang: + files[lang] += 1 + lines[lang] += count + for what, rules in (("ui", UI), ("routes", ROUTES), ("jobs", JOBS), ("data", DATA)): + if _matches(rules, name, text): + has[what].append(name) + found = family_of(dict(lines)) + family = told or found + names = [lang for lang, _ in lines.most_common() if LANGUAGE_FAMILY.get(lang) == family] or [lang for lang, _ in lines.most_common(2)] + if family == "mainframe": # the prompts read "COBOL" as before; PL/I alone, or HLASM alone, names itself + names = ["COBOL"] if "COBOL" in lines else names[:1] + return { + "family": family, "found": found, "told": told, + "languages": {lang: {"files": files[lang], "lines": lines[lang], "family": LANGUAGE_FAMILY.get(lang, "mixed")} + for lang, _ in lines.most_common()}, + "has": {what: {"count": len(has[what]), "files": has[what][:SAMPLE]} for what in ("ui", "routes", "jobs", "data")}, + "skipped": skipped, + "words": {"languages": _joined(names[:2]), **WORDS["mainframe" if family == "mainframe" else "other"]}, + } + + +def _joined(names: list[str]) -> str: + return " and ".join(names) if names else "the source" + + +def profile_archive(archive: Path, told: str | None = None) -> dict[str, Any]: + members = [] + with zipfile.ZipFile(archive) as z: + for m in z.infolist(): + if m.is_dir(): + continue + with z.open(m) as handle: + head = handle.read(READ) + count = head.count(b"\n") + sum(chunk.count(b"\n") for chunk in iter(lambda: handle.read(READ), b"")) + members.append((m.filename, head, count)) + return profile_members(members, told) + + +def profile_folder(root: Path, told: str | None = None) -> dict[str, Any]: + """The same from a folder (the guided run reads a local source before the snapshot).""" + members = [] + for p in sorted(root.rglob("*")): + if p.is_file() and not p.is_symlink(): + rel = p.relative_to(root).as_posix() + data = b"" if _skipped(rel) else p.read_bytes() # counted as skipped, not read + members.append((rel, data[:READ], data.count(b"\n"))) + return profile_members(members, told) + + +def summary(found: dict[str, Any] | None) -> str: + """One line for `reframe status` and the reports.""" + if not found: + return "" + ranked = sorted(found["languages"].items(), key=lambda kv: (-kv[1]["lines"], kv[0])) # the run folder keeps JSON keys sorted + langs = ", ".join(f"{lang} {v['files']} files" for lang, v in ranked[:4]) or "no code found" + has = ", ".join(f"{what} {found['has'][what]['count']}" for what in ("ui", "routes", "jobs", "data") + if found["has"].get(what, {}).get("count")) or "no screens, routes, jobs or data found" + told = f" (told; found {found['found']})" if found.get("told") and found["told"] != found["found"] else "" + return f"{found['family']}{told}: {langs}; {has}" diff --git a/src/reframe/source/snapshot.py b/src/reframe/source/snapshot.py index ef43e38d..90b1a1fb 100644 --- a/src/reframe/source/snapshot.py +++ b/src/reframe/source/snapshot.py @@ -9,7 +9,8 @@ Every archive is checked the same way before it is used: it opens, has no absolute or ".." paths and no links, and unpacks to at most 2 GB. Then the package check (reframe.source.package_check, MP-03) records what AWS -Transform will make of it in package-check.json, before anything is uploaded. +Transform will make of it in package-check.json, before anything is uploaded, and the stack profile +(reframe.source.profile, L1-01) what the codebase is, in stack-profile.json. """ from __future__ import annotations @@ -145,6 +146,10 @@ def take(folder: RunFolder, source: str, ref: str | None, runner: Runner = run_s folder.save(package_check.FILE, checked) folder.event("package_checked", files=checked["files"], unnamed=checked["unnamed"]["count"], disagree=checked["disagree_count"], binary=checked["binary_count"], encodings=",".join(checked["encodings"])) + from reframe.source import profile + stack = profile.profile_archive(archive, folder.state.get("legacy")) # what the codebase is (L1-01), with no model + folder.save(profile.FILE, stack) + folder.event("stack_profiled", family=stack["family"], found=stack["found"], told=stack.get("told") or "") data = archive.read_bytes() record: dict[str, Any] = {"source": source, "ref": ref, "form": form, "commit": commit, "files": files, "sha256": sha256_hex(data), "bytes": len(data), "archive": "source/archive.zip"} diff --git a/tests/source/test_profile.py b/tests/source/test_profile.py new file mode 100644 index 00000000..940e4693 --- /dev/null +++ b/tests/source/test_profile.py @@ -0,0 +1,120 @@ +"""L1-01: the stack profile (docs/any-legacy.md, section 4): languages, family, what the codebase has and the prompts' +words, worked out with no model after the snapshot; `--legacy` overrides the family; status and the reports show it.""" +import contextlib +import io +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +from reframe.core import cli, commands +from reframe.core.runfolder import RunFolder +from reframe.report import build +from reframe.source import profile, snapshot +from tests import stacks + + +class ProfileTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def of(self, name, told=None): + return profile.profile_folder(stacks.write(Path(self.tmp.name) / name, stacks.FIXTURES[name]), told) + + def test_the_family_of_each_fixture(self): + self.assertEqual({name: self.of(name)["family"] for name in stacks.FIXTURES}, + {"java": "java", "dotnet": "dotnet", "web-script": "web-script", "batch": "java", "mainframe": "mainframe", "mixed": "mixed"}) + + def test_what_each_has_with_the_files_that_show_it(self): + java = self.of("java")["has"] + self.assertEqual(java["ui"]["files"], ["src/main/webapp/WEB-INF/jsp/orders/list.jsp", "src/main/webapp/WEB-INF/jsp/orders/new.jsp"]) + self.assertEqual(java["routes"]["files"], ["src/main/java/org/demo/shop/web/OrderController.java"]) + self.assertEqual(java["jobs"]["files"], ["src/main/java/org/demo/shop/jobs/NightlyReport.java"]) + self.assertEqual(java["data"]["files"], ["src/main/java/org/demo/shop/model/Order.java", "src/main/resources/schema.sql"]) + dotnet = self.of("dotnet")["has"] + self.assertEqual(dotnet["routes"]["files"], ["Shop/App_Start/RouteConfig.cs", "Shop/Controllers/OrdersController.cs"]) + self.assertEqual(dotnet["data"]["files"], ["Shop/Data/ShopContext.cs", "Shop/Models/Order.cs"]) + batch = self.of("batch")["has"] + self.assertEqual((batch["ui"]["count"], batch["routes"]["count"]), (0, 0)) # a batch system: no screens, no routes + self.assertEqual(batch["jobs"]["files"], ["deploy/crontab", "src/main/java/org/demo/billing/BillingJobConfig.java"]) + mainframe = self.of("mainframe")["has"] + self.assertEqual(mainframe["ui"]["files"], ["app/bms/MENU00.bms", "app/bms/SIGN00.bms"]) + self.assertEqual(mainframe["routes"]["files"], ["app/csd/DEMO.csd"]) + + def test_libraries_in_the_tree_are_not_counted(self): + java = self.of("java") + self.assertEqual(java["skipped"], 1) # jquery.min.js, in vendor/ + self.assertNotIn("JavaScript", java["languages"]) + self.assertEqual(java["languages"]["Java"]["files"], 4) + + def test_words_for_the_prompts(self): + self.assertEqual(self.of("mainframe")["words"], {"languages": "COBOL", "follow": "a PERFORM, CALL or copybook", "program": "program"}) + self.assertEqual(self.of("java")["words"]["languages"], "Java and JSP") + self.assertEqual(self.of("dotnet")["words"], {"languages": "C# and Razor", "follow": "a call, an include, an import or an inherited method", + "program": "source file"}) + + def test_shared_extensions_by_content(self): + self.assertEqual(profile.language("includes/db.inc", b"\n"), "C") + self.assertIsNone(profile.language("notes.inc", b"just words\n")) + self.assertEqual(profile.language("app/cbl/PROG", " IDENTIFICATION DIVISION.\n".encode()), "COBOL") # a member with no extension + + def test_told_overrides_found(self): + told = self.of("mixed", told="java") + self.assertEqual((told["family"], told["found"], told["told"]), ("java", "mixed", "java")) + self.assertEqual(told["words"]["languages"], "Java") + self.assertTrue(profile.summary(told).startswith("java (told; found mixed): ")) + + def test_the_archive_and_the_folder_agree(self): + root = stacks.write(Path(self.tmp.name) / "zip", stacks.JAVA_WEB) + archive = Path(self.tmp.name) / "java.zip" + with zipfile.ZipFile(archive, "w") as z: + for p in sorted(root.rglob("*")): + if p.is_file(): + z.write(p, p.relative_to(root).as_posix()) + self.assertEqual(profile.profile_archive(archive), profile.profile_folder(root)) + + +class RecordedTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.source = stacks.write(Path(self.tmp.name) / "source", stacks.MIXED) + self.folder = RunFolder(Path(self.tmp.name) / "run") + + def take(self, **state): + self.folder.update(project="demo", source=str(self.source), mode="autonomous", status="RUNNING", stage="snapshot", **state) + no_git = lambda argv, env, timeout, data: subprocess.CompletedProcess(argv, 1, "", "") # noqa: E731 - a plain folder + snapshot.take(self.folder, str(self.source), None, runner=no_git) + return self.folder.load(profile.FILE) + + def test_recorded_after_the_snapshot_shown_by_status_and_the_reports(self): + found = self.take() + self.assertEqual(found["family"], "mixed") + out = io.StringIO() + with mock.patch.object(commands, "find_run", return_value=self.folder), contextlib.redirect_stdout(out): + commands.status(type("Args", (), {"run": None})()) + self.assertIn("Stack", out.getvalue()) + self.assertIn("mixed: Java 4 files, C# 4 files, PHP 2 files; ui 1, routes 3, jobs 1, data 3", out.getvalue().replace("\n", "")) + self.assertNotIn("Package check", out.getvalue()) # what AWS Transform makes of it matters for mainframe code only + self.assertEqual(build._stack(self.folder), profile.summary(found)) + self.assertEqual(build._package(self.folder), {}) + + def test_legacy_recorded_on_the_run_is_what_the_profile_is_told(self): + found = self.take(legacy="dotnet") + self.assertEqual((found["family"], found["found"]), ("dotnet", "mixed")) + + def test_the_legacy_option(self): + args = cli.parser().parse_args(["run", "--source", "x", "--tools", "claude", "--legacy", "java"]) + self.assertEqual(args.legacy, "java") + with mock.patch.object(commands, "start_claude_only", return_value=0) as start: + commands.run(args) + self.assertEqual(start.call_args.kwargs["legacy"], "java") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/stacks.py b/tests/stacks.py new file mode 100644 index 00000000..feadbf14 --- /dev/null +++ b/tests/stacks.py @@ -0,0 +1,309 @@ +"""Small synthetic codebases for release 1.1's tests (docs/any-legacy.md, section 7): a Java web application, a .NET one, +a PHP one, a batch-only one, a mixed one and a mainframe one. Written for the tests, with no code taken from anyone.""" +from __future__ import annotations + +from pathlib import Path + +from tests.design.test_flow import CSD, MENU, MENU_TABLE, SIGNON, bms + +JAVA_WEB = { + "pom.xml": "4.0.0shop\n", + "src/main/java/org/demo/shop/web/OrderController.java": """package org.demo.shop.web; + +import org.demo.shop.model.Order; +import org.demo.shop.service.OrderService; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.*; + +@Controller +@RequestMapping("/orders") +public class OrderController { + private final OrderService service; + + public OrderController(OrderService service) { + this.service = service; + } + + @GetMapping + public String list(org.springframework.ui.Model model) { + model.addAttribute("orders", service.all()); + return "orders/list"; + } + + @PostMapping("/new") + public String create(@RequestParam String customer, @RequestParam int quantity) { + if (quantity <= 0) { + return "redirect:/orders/new?error=quantity"; + } + service.place(customer, quantity); + return "redirect:/orders"; + } +} +""", + "src/main/java/org/demo/shop/service/OrderService.java": """package org.demo.shop.service; + +import java.math.BigDecimal; +import java.util.List; +import org.demo.shop.model.Order; + +public class OrderService { + static final BigDecimal UNIT_PRICE = new BigDecimal("12.50"); + static final BigDecimal DISCOUNT_FROM = new BigDecimal("100.00"); + + public BigDecimal total(int quantity) { + BigDecimal total = UNIT_PRICE.multiply(BigDecimal.valueOf(quantity)); + if (total.compareTo(DISCOUNT_FROM) > 0) { + total = total.multiply(new BigDecimal("0.90")); + } + return total; + } + + public Order place(String customer, int quantity) { + if (customer == null || customer.isBlank()) { + throw new IllegalArgumentException("A customer is required"); + } + return new Order(customer, quantity, total(quantity)); + } + + public List all() { + return List.of(); + } +} +""", + "src/main/java/org/demo/shop/model/Order.java": """package org.demo.shop.model; + +import java.math.BigDecimal; +import javax.persistence.*; + +@Entity +@Table(name = "ORDERS") +public class Order { + @Id @GeneratedValue + private Long id; + @Column(nullable = false, length = 40) + private String customer; + private int quantity; + private BigDecimal total; + + protected Order() {} + + public Order(String customer, int quantity, BigDecimal total) { + this.customer = customer; + this.quantity = quantity; + this.total = total; + } +} +""", + "src/main/java/org/demo/shop/jobs/NightlyReport.java": """package org.demo.shop.jobs; + +import org.springframework.scheduling.annotation.Scheduled; + +public class NightlyReport { + @Scheduled(cron = "0 0 2 * * *") + public void run() { + System.out.println("orders report"); + } +} +""", + "src/main/webapp/WEB-INF/jsp/orders/list.jsp": """<%@ page contentType="text/html" %> + +

Orders

+ + +
${o.customer}${o.quantity}${o.total}
+New order + +""", + "src/main/webapp/WEB-INF/jsp/orders/new.jsp": """<%@ page contentType="text/html" %> + +
+ + + +
+Back + +""", + "src/main/resources/schema.sql": "CREATE TABLE ORDERS (\n ID BIGINT PRIMARY KEY,\n CUSTOMER VARCHAR(40) NOT NULL,\n QUANTITY INT,\n TOTAL DECIMAL(10,2)\n);\n", + "src/main/webapp/js/vendor/jquery.min.js": "!function(e){" + "var a=1;" * 4000 + "}(window);\n", +} + +DOTNET = { + "Shop/Shop.csproj": "net48\n", + "Shop/Web.config": "\n", + "Shop/App_Start/RouteConfig.cs": """using System.Web.Mvc; +using System.Web.Routing; + +namespace Shop +{ + public class RouteConfig + { + public static void RegisterRoutes(RouteCollection routes) + { + routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Orders", action = "Index", id = UrlParameter.Optional }); + } + } +} +""", + "Shop/Controllers/OrdersController.cs": """using System.Linq; +using System.Web.Mvc; +using Shop.Data; +using Shop.Models; + +namespace Shop.Controllers +{ + public class OrdersController : Controller + { + private readonly ShopContext db = new ShopContext(); + + public ActionResult Index() + { + return View(db.Orders.ToList()); + } + + [HttpPost] + public ActionResult Create(Order order) + { + if (order.Quantity <= 0) + { + ModelState.AddModelError("Quantity", "The quantity must be at least one"); + return View(order); + } + order.Total = order.Quantity * 12.50m; + if (order.Total > 100m) + { + order.Total = order.Total * 0.90m; + } + db.Orders.Add(order); + db.SaveChanges(); + return RedirectToAction("Index"); + } + } +} +""", + "Shop/Models/Order.cs": """using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Shop.Models +{ + [Table("Orders")] + public class Order + { + public int Id { get; set; } + [Required, StringLength(40)] + public string Customer { get; set; } + public int Quantity { get; set; } + public decimal Total { get; set; } + } +} +""", + "Shop/Data/ShopContext.cs": """using System.Data.Entity; +using Shop.Models; + +namespace Shop.Data +{ + public class ShopContext : DbContext + { + public DbSet Orders { get; set; } + } +} +""", + "Shop/Views/Orders/Index.cshtml": """@model IEnumerable +

Orders

+ +@foreach (var o in Model) { } +
@o.Customer@o.Quantity@o.Total
+@Html.ActionLink("New order", "Create") +""", + "Shop/Views/Orders/Create.cshtml": """@model Shop.Models.Order +@using (Html.BeginForm("Create", "Orders", FormMethod.Post)) +{ + @Html.TextBoxFor(m => m.Customer) + @Html.TextBoxFor(m => m.Quantity, new { type = "number", min = 1 }) + +} +@Html.ActionLink("Back", "Index") +""", + "Shop/Scripts/jquery-3.7.1.min.js": "!function(e){" + "var a=1;" * 4000 + "}(window);\n", +} + +PHP = { + "index.php": """ + +

Orders

+
+ + + +
+ +""", + "orders.php": """ 100) { + $total = $total * 0.90; +} +save_order($_POST['customer'], $quantity, $total); +header('Location: index.php'); +""", + "includes/db.inc": """prepare('INSERT INTO orders (customer, quantity, total) VALUES (?, ?, ?)')->execute([$customer, $quantity, $total]); +} +""", + "schema.sql": "CREATE TABLE orders (\n id INTEGER PRIMARY KEY,\n customer VARCHAR(40) NOT NULL,\n quantity INT,\n total DECIMAL(10,2)\n);\n", +} + +BATCH = { + "src/main/java/org/demo/billing/BillingJobConfig.java": """package org.demo.billing; + +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableBatchProcessing +public class BillingJobConfig { + public static final String JOB = "monthlyBilling"; +} +""", + "src/main/java/org/demo/billing/InvoiceProcessor.java": """package org.demo.billing; + +import java.math.BigDecimal; + +public class InvoiceProcessor { + static final BigDecimal LATE_FEE = new BigDecimal("15.00"); + + public BigDecimal amountDue(BigDecimal balance, int daysLate) { + if (balance.signum() <= 0) { + return BigDecimal.ZERO; + } + return daysLate > 30 ? balance.add(LATE_FEE) : balance; + } +} +""", + "src/main/resources/schema.sql": "CREATE TABLE INVOICE (\n ID BIGINT PRIMARY KEY,\n BALANCE DECIMAL(12,2) NOT NULL,\n DUE_DATE DATE\n);\n", + "deploy/crontab": "0 1 1 * * /opt/billing/run-job.sh monthlyBilling\n", +} + +MAINFRAME = {"app/bms/SIGN00.bms": bms("SIGN00", "SIGN0A", "ENTER=Sign-on F3=Exit"), "app/bms/MENU00.bms": bms("MENU00", "MENU0A", "ENTER=Go F3=Exit"), + "app/cpy/MENU02Y.cpy": MENU_TABLE, "app/cbl/SIGN00C.cbl": SIGNON, "app/cbl/MENU00C.cbl": MENU, "app/csd/DEMO.csd": CSD} + +MIXED = {**{f"java/{k}": v for k, v in JAVA_WEB.items() if k.endswith(".java")}, **{f"dotnet/{k}": v for k, v in DOTNET.items() if k.endswith(".cs")}, + **{f"php/{k}": v for k, v in PHP.items() if k.endswith(".php")}} +"""Java, C# and PHP, none with more than half the lines.""" + +FIXTURES = {"java": JAVA_WEB, "dotnet": DOTNET, "web-script": PHP, "batch": BATCH, "mainframe": MAINFRAME, "mixed": MIXED} + + +def write(root: Path, files: dict[str, str]) -> Path: + for name, text in files.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_text(text) + return root From ec180ab413ecd02f084da30db76aabed69b93ef5 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:03:01 -0700 Subject: [PATCH 06/13] L1-02: pipelines 1 and 2 by profile Pipeline 1 (docs/any-legacy.md, section 5.1): AWS Transform writes requirements and business rules only for mainframe code, so it is offered only when the stack profile's family is mainframe. - `reframe run --legacy ` other than mainframe, with --tools both or aws, is refused at once with the Claude-only command. - Otherwise the check is at the end of stage 1: after the snapshot has been profiled and before stage 2 makes the first AWS resource. Nothing is created in AWS, and the message gives the Claude-only command. A run from before the profile goes on as a mainframe run. - The guided run does not offer AWS Transform for a local source that is not mainframe code: it says so and goes on as Claude only. Pipeline 2 (section 5.2): a program's name follows the profile. For the mainframe it is still the member name, the file's stem in capitals. For any other family it is the file's path within the source, so two OrderService.java files in different folders stay apart. A rule card joins its module of the plugin's map by the module's name or by its file, in the card's domain, Claude's requirements, its business review and its graph. The plugin's commands, the estimate and the agent limit are unchanged. Tests: the refusal and its place in stage order, mainframe and older runs going on, --legacy with AWS, the guided run on a PHP source, program names by family, and two files of one name kept apart. Prepared with AI assistance. --- src/reframe/claude/graph.py | 3 +- src/reframe/claude/requirements.py | 3 +- src/reframe/claude/retrieve.py | 38 +++++++-- src/reframe/core/commands/starting.py | 6 +- src/reframe/core/guide.py | 25 ++++-- src/reframe/core/pipeline.py | 15 ++++ src/reframe/report/build.py | 3 +- tests/core/test_by_profile.py | 117 ++++++++++++++++++++++++++ 8 files changed, 192 insertions(+), 18 deletions(-) create mode 100644 tests/core/test_by_profile.py diff --git a/src/reframe/claude/graph.py b/src/reframe/claude/graph.py index 1ff1509c..a5159a6b 100644 --- a/src/reframe/claude/graph.py +++ b/src/reframe/claude/graph.py @@ -114,7 +114,8 @@ def build(run: str, sha256: str, model: dict[str, Any], generated: dict[str, Any for ident in step.get("nodes") or []: if ident in node_iri: q.add(s, "involves", node_iri[ident], literal=False) - modules_by_name = {m.get("name", "").upper(): node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri} + from reframe.claude.retrieve import module_keys + modules_by_name = {key: node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri for key in module_keys(m)} rule_iri = {} for card in model.get("rules") or []: r = q.iri("rule", card["id"]) diff --git a/src/reframe/claude/requirements.py b/src/reframe/claude/requirements.py index 3163f196..521e9a1a 100644 --- a/src/reframe/claude/requirements.py +++ b/src/reframe/claude/requirements.py @@ -61,7 +61,8 @@ def domain_input(model: dict[str, Any], domain: dict[str, Any]) -> dict[str, Any]: modules = [m for m in model.get("modules") or [] if m.get("domain") == domain["id"]] - names = {m.get("name", "").upper() for m in modules} + from reframe.claude.retrieve import module_keys + names = {key for m in modules for key in module_keys(m)} members = set(domain.get("members") or []) rules = [r for r in model.get("rules") or [] if r.get("domain") == domain["id"] or r.get("program", "").upper() in names] rule_ids = {r["id"] for r in rules} diff --git a/src/reframe/claude/retrieve.py b/src/reframe/claude/retrieve.py index 04707040..494340cd 100644 --- a/src/reframe/claude/retrieve.py +++ b/src/reframe/claude/retrieve.py @@ -37,13 +37,37 @@ def sections(markdown: str, level: int = 2) -> list[dict[str, str]]: return out -def program_of(path: str) -> str: - """The program name a source path stands for: the file's stem, upper-cased (COBOL member names).""" +def program_of(path: str, family: str = "mainframe") -> str: + """The program name a source path stands for (docs/any-legacy.md, section 5.2). For the mainframe, the file's stem, + upper-cased, as COBOL members are named. For any other family, the file's path within the source, so two files of the + same name in different folders stay apart.""" + if family != "mainframe": + return path_key(path) stem = Path(path).name.split(".")[0] return stem.upper() -def parse_rules(markdown: str) -> list[dict[str, Any]]: +def path_key(path: str) -> str: + """A source path as Reframe compares it: forward slashes, no leading `./` or `/`.""" + return path.replace("\\", "/").lstrip("/").removeprefix("./") + + +def module_keys(module: dict[str, Any]) -> set[str]: + """What a rule card's program may name a module of the plugin's map by, upper-cased: the module's name (a mainframe + member's), and its file's path (any other family's program name).""" + keys = {str(module.get("name") or "").upper()} - {""} + if module.get("file"): + keys.add(path_key(str(module["file"])).upper()) + return keys + + +def family(folder: RunFolder) -> str: + """The run's family from its stack profile (L1-01); a run from before the profile is a mainframe run.""" + from reframe.source import profile + return str((folder.load(profile.FILE) or {}).get("family") or "mainframe") + + +def parse_rules(markdown: str, family: str = "mainframe") -> list[dict[str, Any]]: cards = [] matches = list(RULE.finditer(markdown)) for i, match in enumerate(matches): @@ -74,7 +98,7 @@ def parse_rules(markdown: str) -> list[dict[str, Any]]: "id": match.group(1), "name": match.group(2).strip(), "category": fields.get("category", ""), "priority": fields.get("priority", "").split(" ")[0], "source": source.strip("` "), "path": path, "line": int(where.group(2)) if where else None, "line_end": int(where.group(3)) if where and where.group(3) else None, - "program": program_of(path) if path else "", "plain": fields.get("plain english", ""), + "program": program_of(path, family) if path else "", "plain": fields.get("plain english", ""), "spec": [{"clause": c, "text": t} for c, t in spec], "parameters": fields.get("parameters", ""), "edge_cases": fields.get("edge cases handled", ""), "defect": fields.get("suspected defect", ""), "confidence": level, "confidence_note": confidence[len(level):].strip(" —-") if confidence else ""}) @@ -146,10 +170,10 @@ def text(name: str) -> str: if topology.get("root"): walk(topology["root"], None, parts) rules_md = text("BUSINESS_RULES.md") - cards = parse_rules(rules_md) - module_domain = {m["name"].upper(): m["domain"] for m in parts["modules"] if m.get("name")} + cards = parse_rules(rules_md, family(folder)) + module_domain = {key: m["domain"] for m in parts["modules"] for key in module_keys(m)} for card in cards: - card["domain"] = module_domain.get(card["program"], "") + card["domain"] = module_domain.get(card["program"].upper(), "") result = json.loads(text("rules_result.json") or "{}") if (analysis / "rules_result.json").exists() else {} stats = result.get("stats") if isinstance(result, dict) else None return { diff --git a/src/reframe/core/commands/starting.py b/src/reframe/core/commands/starting.py index f21c62cc..64232c0d 100644 --- a/src/reframe/core/commands/starting.py +++ b/src/reframe/core/commands/starting.py @@ -22,6 +22,10 @@ def run(args) -> int: max_agents=getattr(args, "max_agents", None), auth=auth, profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None, legacy=getattr(args, "legacy", None)) + legacy = getattr(args, "legacy", None) + if legacy and legacy != "mainframe": # AWS Transform is offered only for the mainframe (docs/any-legacy.md, section 5.1) + return commands._fail(Stop(Outcome.REFUSED, f"--legacy {legacy}: AWS Transform writes requirements only for mainframe code, so " + f"this run is Claude only: reframe run --tools claude --legacy {legacy} --source {args.source}")) from reframe.core.setup import load_config saved = load_config() profile = args.profile or saved.get("profile") @@ -30,7 +34,7 @@ def run(args) -> int: both = getattr(args, "tools", "both") == "both" # the Claude assessment alongside, as the guided run offers by default return commands.start(source=args.source, profile=profile, ref=args.ref, mode=args.mode, region=args.region or saved.get("region") or "us-east-1", project=args.project, graph=args.graph, terraform=args.terraform, foreground=args.foreground, - claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=getattr(args, "legacy", None)) + claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=legacy) def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, project: str | None, graph: str | None, diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py index b7b979c8..db18d625 100644 --- a/src/reframe/core/guide.py +++ b/src/reframe/core/guide.py @@ -211,22 +211,24 @@ def check_url(value: str) -> str | None: return str(Path(archive).expanduser().resolve()), None -def stack(chosen_source: str) -> str | None: +def stack(chosen_source: str) -> tuple[str | None, str | None]: """The stack profile of a local source (L1-01), shown before the run starts; asked only when no family carries most of - the code. Returns the family the person chose, or None to keep what was found. A Git URL is profiled after the snapshot.""" + the code. Returns the family (None when it is not known yet) and what the person chose (None to keep what was found). + A Git URL is profiled after the snapshot.""" from reframe.source import profile path = Path(chosen_source) if not path.exists(): ui.hint("The stack profile is worked out after the snapshot; reframe status shows it.") - return None + return None, None with ui.console.status("Working out the stack…"): found = profile.profile_folder(path) if path.is_dir() else profile.profile_archive(path) ui.state("Stack", profile.summary(found), "") if found["found"] != "mixed": - return None + return found["found"], None families = list(profile.FAMILIES) picked = ui.choose("No family carries most of the code. Which is it?", [(f, "") for f in families], len(families)) - return None if families[picked - 1] == "mixed" else families[picked - 1] + told = families[picked - 1] + return told, None if told == "mixed" else told # ---- 4 and 5. choices, summary, start ---------------------------------------------------------------- @@ -373,7 +375,7 @@ def run(args) -> int: if picked_source is None: return 1 chosen, ref = picked_source - legacy = stack(chosen) + _, legacy = stack(chosen) picked = claude_only_choices(chosen) if not claude_only_summary(chosen, ref, picked): ui.hint("Nothing was started or created.") @@ -390,7 +392,16 @@ def run(args) -> int: if picked_source is None: return 1 chosen, ref = picked_source - legacy = stack(chosen) + family, legacy = stack(chosen) + if family and family != "mainframe": # AWS Transform is not offered (docs/any-legacy.md, section 5.1) + ui.warn("AWS Transform writes requirements only for mainframe code, so this run is Claude only, with no AWS.") + picked = claude_only_choices(chosen) + if not claude_only_summary(chosen, ref, picked): + ui.hint("Nothing was started or created.") + return 0 + return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"], + foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"], + auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {})) picked = choices(chosen) if not summary(chosen, ref, sign, picked): ui.hint("Nothing was started or created.") diff --git a/src/reframe/core/pipeline.py b/src/reframe/core/pipeline.py index 282821c0..78a00d0f 100644 --- a/src/reframe/core/pipeline.py +++ b/src/reframe/core/pipeline.py @@ -99,6 +99,20 @@ def prepare(ctx: Context, prompt: Callable[[str], str] | None, say: Callable[[st # ---- the worker ---------------------------------------------------------------------------------- +NOT_MAINFRAME = ("AWS Transform writes requirements and business rules only for mainframe code (docs/any-legacy.md, section 5.1), " + "and this codebase's stack profile is {family}: {summary}. Nothing was created in AWS. Assess it with Claude only: " + "reframe run --tools claude --source {source}") + + +def refuse_unless_mainframe(folder: RunFolder) -> None: + """Stage 1's end: pipeline 1 goes on only for a mainframe codebase, before anything is made in AWS (L1-02).""" + from reframe.source import profile + stack = folder.load(profile.FILE) + if stack and stack.get("family") != "mainframe": + raise Stop(Outcome.REFUSED, NOT_MAINFRAME.format(family=stack["family"], summary=profile.summary(stack), + source=folder.state.get("source", ""))) + + def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome: """Stages 1 to 8. Returns DONE, or raises Stop with the outcome to record. on_resources runs once the run's AWS resources exist (pipeline 2 starts there, alongside this pipeline).""" @@ -108,6 +122,7 @@ def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome names = ctx.names() ctx.stage("snapshot") record = snapshot.take(ctx.folder, state["source"], state.get("ref")) + refuse_unless_mainframe(ctx.folder) ctx.stage("infrastructure") tf = ctx.terraform() diff --git a/src/reframe/report/build.py b/src/reframe/report/build.py index e78f025b..22659bd6 100644 --- a/src/reframe/report/build.py +++ b/src/reframe/report/build.py @@ -334,7 +334,8 @@ def collect_claude(folder: RunFolder) -> dict[str, Any]: entry["capabilities"].append(cap["id"]) functions.append(entry) domain["functions"].append(fid) - names = {m.get("name", "").upper() for m in modules} + from reframe.claude.retrieve import module_keys + names = {key for m in modules for key in module_keys(m)} uncited = [c["id"] for c in model.get("rules") or [] if (c.get("domain") == pdomain.get("id") or c.get("program", "").upper() in names) and c["id"] not in cited_here and c["id"] not in rule_function] open_qs = [q for q in model.get("sme_questions") or [] if q.get("rule") in cards and q["rule"] not in carried diff --git a/tests/core/test_by_profile.py b/tests/core/test_by_profile.py new file mode 100644 index 00000000..791e1b6b --- /dev/null +++ b/tests/core/test_by_profile.py @@ -0,0 +1,117 @@ +"""L1-02: pipelines 1 and 2 by the stack profile (docs/any-legacy.md, sections 5.1 and 5.2). AWS Transform is offered only +for mainframe code and refused before anything is made otherwise; program names follow the profile.""" +import contextlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from reframe.claude import requirements, retrieve +from reframe.core import cli, commands, guide, pipeline, setup +from reframe.core.errors import EXIT_CODES, Outcome, Stop +from reframe.core.runfolder import RunFolder +from reframe.source import profile +from tests import stacks +from tests.core.test_setup import MAC + +JAVA_RULE = """# Business rules: shop + +## Orders + +### RULE-001: An order over 100 is discounted +**Category:** Calculation +**Priority:** P1 +**Source:** `src/main/java/org/demo/shop/service/OrderService.java:13-15` +**Plain English:** Orders over 100 get ten percent off. +**Confidence:** High + +### RULE-002: Same name, another folder +**Category:** Validation +**Priority:** P2 +**Source:** `src/main/java/org/demo/admin/OrderService.java:4` +**Confidence:** High +""" + + +class Pipeline1Test(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.folder = RunFolder(Path(self.tmp.name) / "run") + self.folder.update(source="/src/shop", project="shop", mode="autonomous", status="RUNNING", stage="snapshot") + + def profiled(self, name): + root = stacks.write(Path(self.tmp.name) / name, stacks.FIXTURES[name]) + self.folder.save(profile.FILE, profile.profile_folder(root)) + + def test_refused_after_the_snapshot_before_anything_is_made(self): + self.profiled("java") + with self.assertRaises(Stop) as stop: + pipeline.refuse_unless_mainframe(self.folder) + self.assertEqual(stop.exception.outcome.value, "REFUSED") + self.assertIn("this codebase's stack profile is java", stop.exception.message) + self.assertIn("Nothing was created in AWS", stop.exception.message) + self.assertIn("reframe run --tools claude --source /src/shop", stop.exception.message) + + def test_the_stage_order(self): + """Stage 1 ends with the check, and stage 2 makes the first AWS resource: nothing is made before the refusal.""" + import inspect + work = inspect.getsource(pipeline.work) + self.assertLess(work.index("snapshot.take"), work.index("refuse_unless_mainframe")) + self.assertLess(work.index("refuse_unless_mainframe"), work.index('ctx.stage("infrastructure")')) + + def test_mainframe_and_runs_from_before_the_profile_go_on(self): + pipeline.refuse_unless_mainframe(self.folder) # no profile: a run from before release 1.1 + self.profiled("mainframe") + pipeline.refuse_unless_mainframe(self.folder) + + def test_legacy_other_than_mainframe_with_aws_is_refused_at_once(self): + for tools in ("both", "aws"): + args = cli.parser().parse_args(["run", "--source", "/src/shop", "--tools", tools, "--legacy", "dotnet"]) + with mock.patch.object(commands, "start") as start, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(commands.run(args), EXIT_CODES[Outcome.REFUSED]) + start.assert_not_called() + args = cli.parser().parse_args(["run", "--source", "/src/shop", "--tools", "both", "--legacy", "mainframe", "--profile", "p"]) + with mock.patch.object(commands, "start", return_value=0) as start: + commands.run(args) + self.assertEqual(start.call_args.kwargs["legacy"], "mainframe") + + def test_the_guided_run_does_not_offer_aws_transform(self): + source = str(stacks.write(Path(self.tmp.name) / "web", stacks.PHP)) + picked = {"mode": "autonomous", "project": "web", "claude": {"auth": "subscription", "max_agents": 600}} + with mock.patch("reframe.core.ui.interactive", return_value=True), mock.patch.object(setup, "machine", return_value=MAC), \ + mock.patch.object(guide, "which_tools", return_value="both"), mock.patch.object(guide, "prerequisites", return_value=True), \ + mock.patch.object(guide, "sign_in", return_value=type("S", (), {"profile": "p", "region": "r"})()), \ + mock.patch.object(guide, "source", return_value=(source, None)), mock.patch.object(guide, "choices") as aws_choices, \ + mock.patch.object(guide, "claude_only_choices", return_value=picked), mock.patch.object(guide, "claude_only_summary", return_value=True), \ + mock.patch.object(commands, "start") as start, mock.patch.object(commands, "start_claude_only", return_value=0) as alone, \ + contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(guide.run(type("Args", (), {})()), 0) + aws_choices.assert_not_called() + start.assert_not_called() + alone.assert_called_once() + self.assertIn("Claude only", out.getvalue()) + + +class Pipeline2Test(unittest.TestCase): + def test_program_names_follow_the_profile(self): + self.assertEqual(retrieve.program_of("app/cbl/PROG1.cbl"), "PROG1") + self.assertEqual(retrieve.program_of("./src/main/java/org/x/OrderService.java", "java"), "src/main/java/org/x/OrderService.java") + cards = retrieve.parse_rules(JAVA_RULE, "java") + self.assertEqual([c["program"] for c in cards], + ["src/main/java/org/demo/shop/service/OrderService.java", "src/main/java/org/demo/admin/OrderService.java"]) + self.assertEqual([c["program"] for c in retrieve.parse_rules(JAVA_RULE)], ["ORDERSERVICE", "ORDERSERVICE"]) # the mainframe rule + + def test_a_rule_joins_its_module_by_file_outside_the_mainframe(self): + model = {"modules": [{"id": "m1", "name": "OrderService", "domain": "dom:orders", "file": "src/main/java/org/demo/shop/service/OrderService.java"}], + "rules": [{"id": "RULE-001", "program": "src/main/java/org/demo/shop/service/OrderService.java", "domain": ""}, + {"id": "RULE-002", "program": "src/main/java/org/demo/admin/OrderService.java", "domain": ""}], + "flows": []} + given = requirements.domain_input(model, {"id": "dom:orders", "name": "Orders", "members": ["m1"]}) + self.assertEqual([r["id"] for r in given["rules"]], ["RULE-001"]) # the other OrderService stays apart + self.assertEqual(retrieve.module_keys(model["modules"][0]), {"ORDERSERVICE", "SRC/MAIN/JAVA/ORG/DEMO/SHOP/SERVICE/ORDERSERVICE.JAVA"}) + + +if __name__ == "__main__": + unittest.main() From 5120242f832c613e74d5c61d44ba889e1d11e6ec Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:05:58 -0700 Subject: [PATCH 07/13] L1-03: a reconciliation in the stack's words The reconciliation takes its words and its source files from the stack profile (docs/any-legacy.md, section 5.3). - The prompts of the decision, the description of agreed rules and the accuracy audit are written for the mainframe, and for a mainframe run they are exactly as before. For any other stack, Reframe puts them in the stack's words: readers "who do not read Java and JSP"; "follow a call, an include, an import or an inherited method" in place of "a PERFORM, CALL or copybook"; and the reachability check speaks of entry points reached from a route, a page or form, a menu, a call, an event or a scheduled job, not of XCTL, LINK and job cards. The rules keep their business form (WHEN ..., THE ... SHALL ...). - The source files read are those of the profile's languages. For any family but the mainframe, each file stands for itself, keyed by its path, as its program name is (L1-02). Libraries kept in the tree are left out. - The evidence check is unchanged: every cited line must exist in the snapshot. - The expert's pack says which stack the source is, and its guide uses the stack's words. Tests: every mainframe prompt is the same object as before; Java's and .NET's words; the source files and the evidence check on the Java fixture; the audit's prompts and the expert's pack on a Java run. Prepared with AI assistance. --- src/reframe/reconcile/audit.py | 3 +- src/reframe/reconcile/decide.py | 3 +- src/reframe/reconcile/describe.py | 3 +- src/reframe/reconcile/expert.py | 11 ++- src/reframe/reconcile/inputs.py | 23 ++++-- src/reframe/source/profile.py | 30 +++++++- tests/reconcile/test_stack_words.py | 112 ++++++++++++++++++++++++++++ 7 files changed, 168 insertions(+), 17 deletions(-) create mode 100644 tests/reconcile/test_stack_words.py diff --git a/src/reframe/reconcile/audit.py b/src/reframe/reconcile/audit.py index 3973c381..77736290 100644 --- a/src/reframe/reconcile/audit.py +++ b/src/reframe/reconcile/audit.py @@ -205,7 +205,8 @@ def one(number: int, batch: list[dict[str, Any]]) -> None: step_name = f"audit-{label}-b{number}{'-retry' if attempt == 2 else ''}" path = work / f"{step_name}.json" path.write_text(json.dumps({"items": [shown(i, i["id"] in with_note) for i in pending.values()]}, indent=1)) - prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") + from reframe.source import profile + prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") if attempt == 2: prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items())) step = claude.run(step_name, prompt, timeout=3600, schema=SCHEMA) diff --git a/src/reframe/reconcile/decide.py b/src/reframe/reconcile/decide.py index 0b347869..8ad8db37 100644 --- a/src/reframe/reconcile/decide.py +++ b/src/reframe/reconcile/decide.py @@ -211,7 +211,8 @@ def _prompt(self, path: Path) -> str: + ("; " if documents and answers else "") + (f"answered SME questions in analysis/{project}/reframe/reconcile/{self.name}-answers.json" if answers else "") + ".") from reframe.reconcile.units import one_tool - return one_tool(self.folder, PROMPT.format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}", + from reframe.source import profile + return one_tool(self.folder, profile.in_words(PROMPT, profile.of_run(self.folder)).format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}", legacy=f"legacy/{project}", context=context, kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE), ONE_TOOL) def answers(self) -> list[dict[str, Any]]: diff --git a/src/reframe/reconcile/describe.py b/src/reframe/reconcile/describe.py index 5e31e46d..89ae5db9 100644 --- a/src/reframe/reconcile/describe.py +++ b/src/reframe/reconcile/describe.py @@ -122,7 +122,8 @@ def one(b: dict[str, Any]) -> None: path = folder_in / f"{name}{'-retry' if attempt == 2 else ''}.json" path.write_text(json.dumps({"rules": [{"key": i["key"], "program": i["program"], "name": i["name"], "text": i["text"], "cites": i["cites"]} for i in todo.values()]}, indent=1)) - prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", + from reframe.source import profile + prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE) if attempt == 2: prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items())) diff --git a/src/reframe/reconcile/expert.py b/src/reframe/reconcile/expert.py index 2790ec9c..d8f9c0b0 100644 --- a/src/reframe/reconcile/expert.py +++ b/src/reframe/reconcile/expert.py @@ -77,7 +77,7 @@ def blind(item: dict[str, Any], with_note: bool) -> dict[str, Any]: "defect_note": item["defect_note"] if with_note else ""} -def page(rows: list[dict[str, Any]], project: str, origin: str) -> str: +def page(rows: list[dict[str, Any]], project: str, origin: str, guide_text: str = GUIDE) -> str: def code(ex: dict[str, Any]) -> str: if ex["missing"]: return f"

{html.escape(ex['cite'])}: not in the snapshot

" @@ -87,7 +87,7 @@ def code(ex: dict[str, Any]) -> str: f"

{r['id']} {html.escape(r['program'])}

{html.escape(r['rule'])}

" + (f"

Possible defect: {html.escape(r['defect_note'])}

" if r["defect_note"] else "") + "".join(code(ex) for ex in r["excerpts"]) + "
" for r in rows) - guide = html.escape(GUIDE).replace("\n\n", "

").replace("\n", " ") + guide = html.escape(guide_text).replace("\n\n", "

").replace("\n", " ") guide = re.sub(r"\*\*(.+?)\*\*", r"\1", re.sub(r"`(.+?)`", r"\1", guide)) return f""" Expert check: {html.escape(project)}

-

Legacy screens · Screen flow · Journeys · -Modern screens · Prototype · {e(folder.state.get('project') or '')}

-

The design

+{nav} +

The design

{why}

The modernized application's design, from the reconciled requirements and rules: the screens, the journeys, and a final specification for every capability. A capability in a signed-off function is final; every other one is draft. Reframe assembled each specification and checked every requirement, rule, screen and copybook it cites; a Claude step per function wrote the summaries, {c['written']} acceptance criteria for requirements diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py index f90ac536..78823390 100644 --- a/src/reframe/design/package.py +++ b/src/reframe/design/package.py @@ -502,10 +502,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: files[f"{base}/design.md"] = design_md(s, books) files[f"{base}/tasks.md"] = tasks_md(s, ts[s["id"]]) # Claude Code + has_ui = bool(prototype and prototype.is_file()) # a codebase with no screens has no prototype (L1-04) index = "\n".join(f"- [{s['id']} {md(s['title'])}](specs/{s['folder']}.md): {s['status']}, {s['runs_as']}" for s in specs) files["claude-code/CLAUDE.md"] = "\n".join([ f"# {project}, modernized", "", "Build the modernized application from the specifications here. Each capability's specification is in `specs/`; " - "the build tasks, each for a role, are in `tasks.md`; the prototype in `ui-reference/index.html` is the UI to build to; the data contracts are in " + "the build tasks, each for a role, are in `tasks.md`; " + ("the prototype in `ui-reference/index.html` is the UI to build to; " if has_ui else + "the legacy codebase has no screens, so there is no prototype: the capabilities run as jobs or services; ") + "the data contracts are in " "`data-contracts.md`; `traceability.md` takes every ID back to the legacy source.", "", "## Target stack", "", stack_md(stack, context.get("architecture", "")), "", "## Conventions", ""] + conventions() + ["", "## House conventions", "", handover.house(context.get("style", "")), "", "## Skills", "", "In `.claude/skills/`: " + ", ".join(f"`{n}`" for n in handover.SKILLS) + ". Fill in their placeholders first; START-HERE.md says how.", "", @@ -514,7 +516,8 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n" for s in specs: files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books) - files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. " + if has_ui: + files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. " "Each screen is a route (`#/`); *Show the legacy screen* shows the 3270 screen it replaces.\n") # Spec Kit files["spec-kit/.specify/memory/constitution.md"] = "\n".join([ @@ -653,7 +656,7 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]: books = (folder.load("design/contracts.json") or {}).get("contracts") or {} stack = folder.load(STACK) or None journeys = (folder.load("design/journeys.json") or {}).get("journeys") or [] - prototype = folder.path("outputs/design/prototype/index.html") + prototype = None if (folder.load("design/modern.json") or {}).get("left_out") else folder.path("outputs/design/prototype/index.html") project = folder.state.get("project") or "the application" have = versions(folder) latest = folder.path(f"{FOLDER}/v{have[-1]}") if have else None diff --git a/src/reframe/design/pipeline.py b/src/reframe/design/pipeline.py index f1c4d961..3d17a206 100644 --- a/src/reframe/design/pipeline.py +++ b/src/reframe/design/pipeline.py @@ -223,6 +223,9 @@ def changes_md(n: int, report: dict[str, Any]) -> str: out += ["## The context", ""] + [f"- Added {f}" for f in ctx["added"]] + [f"- Changed {f}" for f in ctx["changed"]] + [f"- Removed {f}" for f in ctx["removed"]] + [""] for stage, title in (("journeys", "Journeys"), ("screens", "Modern screens"), ("specs", "Final specifications")): r = report["stages"].get(stage) or {"redone": [], "kept": []} + if r.get("left_out"): + out += [f"## {title}", "", "- Left out: the codebase has no screens.", ""] + continue out += [f"## {title}", ""] out += [f"- Made: {x['name'] or 'No domain'} (new)." if x["changed"] == ["new"] else f"- Redone: {x['name'] or 'No domain'}, because {words(stage, x['changed'])}." for x in r["redone"]] @@ -242,6 +245,19 @@ def changes_md(n: int, report: dict[str, Any]) -> str: return "\n".join(out).rstrip() + "\n" +def without_screens(stack: dict[str, Any], found: dict[str, Any]) -> str: + """Why the design has no screens (L1-04, docs/any-legacy.md section 5.4), or "" when it has some: no reader found a + screen and the stack profile found no screen definitions, views, templates or forms.""" + if found.get("screens") or (stack.get("has") or {}).get("ui", {}).get("count"): + return "" + has = stack.get("has") or {} + what = ("a batch system" if has.get("jobs", {}).get("count") and not has.get("routes", {}).get("count") + else "a service" if has.get("routes", {}).get("count") else "a library") + return (f"This codebase has no screens: it looks like {what}, and Reframe found no screen definitions, views, templates or forms in it. " + "The journeys, the modern screens and the prototype are left out; the final specifications, golden datasets, package and " + "backlog are written as for any codebase.") + + def run(folder, claude, context: Path | None = None, stack: str | None = None, plan_only: bool = False) -> dict[str, Any]: from reframe.claude.workspace import paths from reframe.design import designpage, flow, flowpage, inventory, journeypage, journeys, legacy, modernpage, package, prototype, screens, specs @@ -259,10 +275,15 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p "context_files": {"added": sorted(set(got["files"]) - set(before)), "removed": sorted(set(before) - set(got["files"])), "changed": sorted(f for f in got["files"] if f in before and before[f] != got["files"][f])}, "signoffs": got["signoffs"], "journey_signoffs": got["journey_signoffs"], "ignored": got["ignored"]} + from reframe.source import profile + left_out = without_screens(profile.of_run(folder), inventory.inventory(paths(folder)["legacy"])) if plan_only: - report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"] - report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"] - report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"])["round"] + if left_out: + report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out} + else: + report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"] + report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"] + report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"], screenless=bool(left_out))["round"] report["note"] = "Screens and specifications whose journeys or screens a redone part changes are redone too; this plan cannot see those yet." return report folder.update(design={**state, "round": number, "status": "running", "context": str(context) if context else "", "started_at": iso()}) @@ -274,18 +295,23 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p linked["problems"] = flow.check(linked, legacy_folder) folder.save("design/flow.json", linked) flowpage.draw(folder, found, linked) - value = journeys.run(folder, claude, context, for_journeys) - journeypage.draw(folder, value) - report["stages"]["journeys"] = value["round"] - for_journeys, for_screens, for_specs = routers(folder, got, routed) - value = screens.run(folder, claude, context, for_screens) - modernpage.draw(folder, value) - report["stages"]["screens"] = value["round"] - data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"), - (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "") - prototype.draw(folder, data, got["tokens"]) + if left_out: # a batch system, a service or a library: no journeys, modern screens or prototype, and the page says why + folder.save("design/journeys.json", {"journeys": [], "left_out": left_out}) + folder.save("design/modern.json", {"screens": [], "domains": {}, "counts": {}, "left_out": left_out}) + report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out} + else: + value = journeys.run(folder, claude, context, for_journeys) + journeypage.draw(folder, value) + report["stages"]["journeys"] = value["round"] + for_journeys, for_screens, for_specs = routers(folder, got, routed) + value = screens.run(folder, claude, context, for_screens) + modernpage.draw(folder, value) + report["stages"]["screens"] = value["round"] + data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"), + (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "") + prototype.draw(folder, data, got["tokens"]) for_journeys, for_screens, for_specs = routers(folder, got, routed) - value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"]) + value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"], screenless=bool(left_out)) designpage.draw(folder, value) report["stages"]["specs"] = value["round"] report["problems"] = value["problems"] diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index faa0ed87..4ed7b603 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -397,7 +397,8 @@ def stack_of(folder, stack: str | None) -> dict[str, Any] | None: return folder.load(STACK) or None -def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]: +def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None, + screenless: bool = False) -> dict[str, Any]: """D6. `more(name, data)` gives a batch's extra input for a round (the decisions that name its capabilities); `signoffs` adds sign-offs read in the round; `plan_only` says what would be redone, and why, without a step.""" from reframe.claude.steps import stop_for @@ -407,7 +408,7 @@ def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = F project = folder.state["project"] if not (folder.load("outputs/reconcile/requirements.json") or {}).get("functions"): raise ValueError("run the reconciliation first") - if not folder.load("design/modern.json"): + if not screenless and not folder.load("design/modern.json"): # a codebase with no screens has none to wait for (L1-04) raise ValueError("run the screen inventory, the flow, the journeys and the modern screens first") target = stack_of(folder, None if plan_only else stack) types = data_contracts.stack_types(target) diff --git a/tests/design/test_no_screens.py b/tests/design/test_no_screens.py new file mode 100644 index 00000000..17e4a245 --- /dev/null +++ b/tests/design/test_no_screens.py @@ -0,0 +1,92 @@ +"""L1-04: a design without screens (docs/any-legacy.md, section 5.4). A batch or service codebase gets its specifications, +golden datasets, package and backlog, with the journeys, modern screens and prototype left out and the page saying why.""" +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from reframe.core.runfolder import new_run +from reframe.design import pipeline +from reframe.report import backlog +from reframe.source import profile +from tests import stacks +from tests.design.test_specs import written +from tests.reconcile.test_decide import FakeClaude + +FEE = "rec/u:fee/1" +RULES = [{"key": FEE, "program": "src/main/java/org/demo/billing/InvoiceProcessor.java", "function": "Billing/Invoice", "kind": "business", + "name": "Late fee", "confidence": "high", "text": "WHEN an invoice is more than 30 days late, THE billing job SHALL add a late fee of 15.00", + "covers": ["u/fee-orig"], "evidence": ["src/main/java/org/demo/billing/InvoiceProcessor.java:12"], + "entry": ["src/main/java/org/demo/billing/BillingJobConfig.java:6"], + "examples": [{"given": [{"field": "daysLate", "value": "31"}, {"field": "balance", "value": "100.00"}], "then": "the amount due is 115.00"}]}] +REQUIREMENTS = { + "complete": True, + "domains": [{"key": "billing", "name": "Billing", "functions": ["Billing/Invoice"]}], + "names": {"Billing/Invoice": {"name": "Invoice customers"}}, + "functions": {"Billing/Invoice": {"capabilities": [{ + "number": 1, "title": "Charge late fees", "story": "As the finance team, I want late invoices to carry a fee", "risk": "high", "touches": ["money"], + "questions": [], "tables": [], + "requirements": [{"code": "REQ-F-001", "kind": "functional", "pattern": "event-driven", "rules": [FEE], + "text": "When an invoice is more than 30 days late, the system shall add a late fee of 15.00."}]}]}}, +} + + +def unexpected(data): + raise AssertionError("no journey or screen step runs for a codebase with no screens") + + +class NoScreensTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name}) + env.start() + self.addCleanup(env.stop) + self.folder = new_run("billing") + self.folder.update(project="billing", tools="claude") + legacy = stacks.write(self.folder.root / "claude" / "legacy" / "billing", stacks.BATCH) + self.folder.save(profile.FILE, profile.profile_folder(legacy)) + self.folder.save("snapshot.json", {"sha256": "abc"}) + self.folder.save("outputs/reconcile/requirements.json", REQUIREMENTS) + self.folder.save("outputs/reconcile/rules.json", {"rules": RULES}) + self.folder.save("reconcile/questions.json", {"questions": []}) + self.claude = FakeClaude(journeys=unexpected, screens=unexpected, specs=written) + self.claude.root = self.folder.root / "claude" + + def test_the_reason_names_what_the_codebase_is(self): + stack = self.folder.load(profile.FILE) + why = pipeline.without_screens(stack, {"screens": []}) + self.assertIn("it looks like a batch system", why) + self.assertEqual(pipeline.without_screens(stack, {"screens": [{"map": "M"}]}), "") # a reader found screens + java = profile.profile_folder(stacks.write(Path(self.tmp.name) / "web", stacks.JAVA_WEB)) + self.assertEqual(pipeline.without_screens(java, {"screens": []}), "") # views exist: not left out + + def test_specifications_golden_datasets_package_and_backlog_without_screens(self): + value = pipeline.run(self.folder, self.claude) + for stage in ("journeys", "screens"): + self.assertIn("no screens", value["stages"][stage]["left_out"]) + self.assertEqual([c[0].split("-")[0] for c in self.claude.other_calls], ["specs"]) # only the specifications' step + self.assertEqual(value["stages"]["specs"]["redone"][0]["name"], "Billing/Invoice") + self.assertFalse(self.folder.path("outputs/design/prototype/index.html").exists()) + self.assertIn("- Left out: the codebase has no screens.", self.folder.path("design/changes-1.md").read_text()) + page = self.folder.path("outputs/design/index.html").read_text() + self.assertIn("No screens.", page) + self.assertNotIn('href="prototype/index.html"', page) + self.assertNotIn("legacy screens", page) + root = Path(value["package"]["path"]) + claude_md = (root / "claude-code/CLAUDE.md").read_text() + self.assertIn("the legacy codebase has no screens, so there is no prototype", claude_md) + self.assertFalse((root / "claude-code/ui-reference").exists()) + self.assertTrue(list(root.rglob("golden/*")), "golden datasets are written") + self.assertTrue(list((root / "kiro/.kiro/specs").iterdir())) + made = backlog.export(self.folder, "jira", Path(self.tmp.name) / "jira.csv") + self.assertEqual(made["counts"]["stories"], 1) + + def test_the_plan_says_so_too(self): + plan = pipeline.run(self.folder, self.claude, plan_only=True) + self.assertIn("no screens", plan["stages"]["journeys"]["left_out"]) + + +if __name__ == "__main__": + unittest.main() From 41feba181c0d752bf9f0765c1aa09aa83c258db4 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:19:57 -0700 Subject: [PATCH 09/13] L1-05: screens and flow from any stack For a codebase that is not a mainframe, the design reads its screens and the flow between them with a general reader, reframe.design.general (docs/any-legacy.md, section 5.4). It gives the later stages the same shapes the BMS and CICS readers give, so the journeys, the modern screens and the prototype work as on the mainframe. - Screens (D1): one Claude step per batch of the views, pages and forms the stack profile found lists each screen's fields (name, label, kind, validation) and actions (buttons, links, submits), each citing its line. Reframe checks that every screen names a file of the batch and every cited line exists. A failed answer is asked again once with the reasons; then the screen is kept with no fields and the reasons, never guessed. - Flow (D2): links read with no model where a pattern settles them: an href, a form's action, a redirect, Spring and JAX-RS route annotations, Stripes' @UrlBinding, the ASP.NET MVC conventions (Html.ActionLink, Html.BeginForm, View(), RedirectToAction) and a script page's own path. The ends of a link are view files and routes, and each route stands for the screens it renders, or those it redirects to. A link no pattern settles goes to one Claude step, checked the same way (its target must be a screen, a route or a file, and its lines must exist). What fails twice stays unresolved. - The code behind a screen is its view, the handlers that render it and the classes they use, so a screen reaches the domain of the rules in its service. - The legacy screens page shows a general screen as its fields and actions with their lines and its source file; the old page is not drawn. The flow page and the design page say which reader made them. - The journeys, modern screens and specifications prompts speak of screens, actions and links, not 3270 maps and function keys, for any stack but the mainframe, whose prompts are unchanged. Tests: the Java, .NET and PHP fixtures' screens, links by pattern, reach and the code behind each screen; an answer that fails twice; a link only a model step settles; the prompts' words; and a whole design round on the Java fixture through to the prototype and the specifications. Prepared with AI assistance. --- src/reframe/design/designpage.py | 8 +- src/reframe/design/flowpage.py | 16 +- src/reframe/design/general.py | 458 +++++++++++++++++++++++++++++++ src/reframe/design/journeys.py | 5 +- src/reframe/design/legacy.py | 36 ++- src/reframe/design/pipeline.py | 21 +- src/reframe/design/screens.py | 3 +- src/reframe/design/specs.py | 3 +- src/reframe/source/profile.py | 30 ++ tests/design/test_general.py | 228 +++++++++++++++ tests/source/test_profile.py | 2 +- tests/stacks.py | 7 +- 12 files changed, 799 insertions(+), 18 deletions(-) create mode 100644 src/reframe/design/general.py create mode 100644 tests/design/test_general.py diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py index 14a39571..393b9fbc 100644 --- a/src/reframe/design/designpage.py +++ b/src/reframe/design/designpage.py @@ -173,10 +173,16 @@ def draw(folder, value: dict[str, Any]) -> Path: '

Legacy screens · Screen flow · Journeys ·\n' f'Modern screens · Prototype · {e(folder.state.get("project") or "")}

') why = f'\n

No screens. {e(left_out)}

' if left_out else "" + links = (folder.load("design/flow.json") or {}).get("counts") or {} + reader = ("" if left_out else + f'\n

Screens and flow read by Reframe\'s general reader: each view\'s fields and actions by a Claude step whose ' + f'every cited line Reframe checked; {links.get("by_pattern", 0)} links by the code\'s patterns with no model, {links.get("by_model", 0)} by a ' + f'checked Claude step, {links.get("unresolved", 0)} left open.

' if inventory.get("reader") == "general" else + '\n

Screens and flow read by Reframe\'s BMS and CICS readers, with no model.

') body = f""" The design
{nav} -

The design

{why} +

The design

{why}{reader}

The modernized application's design, from the reconciled requirements and rules: the screens, the journeys, and a final specification for every capability. A capability in a signed-off function is final; every other one is draft. Reframe assembled each specification and checked every requirement, rule, screen and copybook it cites; a Claude step per function wrote the summaries, {c['written']} acceptance criteria for requirements diff --git a/src/reframe/design/flowpage.py b/src/reframe/design/flowpage.py index 54e77e35..673007b7 100644 --- a/src/reframe/design/flowpage.py +++ b/src/reframe/design/flowpage.py @@ -15,7 +15,8 @@ from reframe.design.legacy import STYLE PAGE = "outputs/design/flow.html" -KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction"} +KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction", + "href": "link", "form": "form", "redirect": "redirect", "renders": "renders"} # the last four: the general reader's (L1-05) def _cites(lines: list[str]) -> str: @@ -160,15 +161,20 @@ def draw(folder, screens: dict[str, Any], found: dict[str, Any]) -> Path: + (f" · from {', '.join(_target(c, screens_of, titles) for c in comes)}" if comes else "") + "

" + ('
' + "".join(rows) + "
ByGoes toLines
" if rows else '

No transfer found from this screen.

')) - unresolved = "".join(f"
  • {html.escape(u['program'])} {html.escape(u['kind'])} {html.escape(u['expression'])} at " - f"{_cites(u['lines'])}
  • " for u in found["unresolved"]) or '
  • None.
  • ' + unresolved = "".join(f"
  • {html.escape(u.get('program') or u.get('from', ''))} {html.escape(u['kind'])} " + f"{html.escape(u.get('expression') or u.get('to', ''))} at {_cites(u['lines'])}" + + (f" ({html.escape(u['why'])})" if u.get("why") else "") + "
  • " for u in found["unresolved"]) or '
  • None.
  • ' c = found["counts"] + read = (f"Read by Reframe's general reader: {c['by_pattern']} links settled by the code's patterns (links, forms, redirects, routes and the views " + f"they render), with no model, and {c['by_model']} by a checked Claude step; each with the lines that show it. " + f"{len(found['unresolved'])} link(s) the source leaves open." if found.get("reader") == "general" else + f"Read from the source with no model: {c['transaction']} transactions, {c['xctl']} transfers, {c['link']} calls, {c['return']} returns to " + f"another transaction and {c['key']} key links, each with the lines that show it. {len(found['unresolved'])} transfer(s) the source leaves open.") body = f""" Screen flow

    Legacy screens · {html.escape(folder.state.get('project') or '')}

    How the screens connect

    -

    Read from the source with no model: {c['transaction']} transactions, {c['xctl']} transfers, {c['link']} calls, {c['return']} returns to another -transaction and {c['key']} key links, each with the lines that show it. {len(found['unresolved'])} transfer(s) the source leaves open.

    +

    {read}

    Map

    Columns by distance from the screens nothing leads to. Arrows: transfers, menu options and keys that move forward. F3, F12, returns to the screen a user came from, links to an earlier column and transfers to the sign-on are left out; each screen below lists them.

    {diagram(screens, found)} diff --git a/src/reframe/design/general.py b/src/reframe/design/general.py new file mode 100644 index 00000000..d3f148e1 --- /dev/null +++ b/src/reframe/design/general.py @@ -0,0 +1,458 @@ +"""Pipeline 4, stages D1 and D2 for any stack: the general reader (L1-05, docs/any-legacy.md section 5.4). + +For a codebase that is not a mainframe, the design reads its screens and the flow between them from the views, pages and +forms the stack profile found, and gives later stages the same shapes the BMS and CICS readers give (design/screens.json +and design/flow.json), so the journeys, the modern screens and the prototype work as they do on the mainframe. + +- **Screens (D1):** one Claude step per batch of view files lists each screen's fields (name, label, kind, validation) + and actions (buttons, links, submits), each citing its line. Reframe checks the answer: every screen names a file of + the batch, every cited line exists. An answer that fails is asked again once with the reasons; then the file's screen + is kept with no fields and the reasons, never guessed. +- **Flow (D2):** links read with no model where a pattern settles them: an `href`, a form's `action`, a redirect, a + route annotation (`@RequestMapping` and its kin, `@UrlBinding`, `@Path`), the MVC conventions (a controller's action + renders `Views//`, `return "orders/list"` renders that view), and a script page's own path. A link + no pattern settles goes to one Claude step, checked the same way: its target must be a screen, a route or a file that + exists, and its lines must exist. What fails twice stays unresolved. + +Every link and field cites `:` in the snapshot. Nothing here changes the source. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from collections import defaultdict +from pathlib import Path, PurePosixPath +from typing import Any + +FILE = "design/general.json" +BATCH_FILES, BATCH_BYTES = 8, 60_000 +METHOD = "general-1" + +SCREENS_PROMPT = """Read {input}. It holds the view, page and form files of a legacy {languages} application, each with its lines numbered. The legacy source is under {legacy}/ if you need more; do not change anything. + +For each file, give the screen it shows ("files", one entry per file, "file" exactly as listed): its "title" (what a user would call the screen), and +- "fields": every data field: "name" (the input's name or the property it binds, as written), "label" (the visible label, or empty), "kind" ("input" for what the person enters or chooses, "output" for what the screen only shows), "validation" (what the markup or the code checks for it: required, a length, a range, a pattern; empty if nothing) and "line" (the line it is on); +- "actions": every button, link and submit: "label" (as shown), "kind" ("button", "link" or "submit"), "target" (the URL, route, action or file it goes to, exactly as written, or empty) and "line". + +Use only what the files show. Cite only lines that exist. A file that is a fragment or layout with no fields or actions of its own gets empty lists. Answer only with the JSON.""" + +LINKS_PROMPT = """Read {input}. It holds the links in a legacy {languages} application whose target Reframe could not settle from the code's patterns, each with the lines it was found on, and the screens and routes Reframe knows. The legacy source is under {legacy}/; do not change anything. + +For each link ("links", one entry per link, "id" exactly as listed), say what it leads to: "to" is a screen id from "screens", a route from "routes", a source file path relative to {legacy}/, or empty if the source cannot show it; "lines" are the lines that show it, as ":". Answer only with the JSON.""" + +RETRY = """Your answer failed Reframe's checks. Answer again with the whole JSON, fixing these: + +{problems}""" + +SCREENS_SCHEMA = {"type": "object", "required": ["files"], "properties": {"files": {"type": "array", "items": { + "type": "object", "required": ["file", "title", "fields", "actions"], "properties": { + "file": {"type": "string"}, "title": {"type": "string"}, + "fields": {"type": "array", "items": {"type": "object", "required": ["name", "label", "kind", "validation", "line"], "properties": { + "name": {"type": "string"}, "label": {"type": "string"}, "kind": {"type": "string", "enum": ["input", "output"]}, + "validation": {"type": "string"}, "line": {"type": "integer"}}}}, + "actions": {"type": "array", "items": {"type": "object", "required": ["label", "kind", "target", "line"], "properties": { + "label": {"type": "string"}, "kind": {"type": "string", "enum": ["button", "link", "submit"]}, "target": {"type": "string"}, + "line": {"type": "integer"}}}}}}}}} +LINKS_SCHEMA = {"type": "object", "required": ["links"], "properties": {"links": {"type": "array", "items": { + "type": "object", "required": ["id", "to", "lines"], "properties": {"id": {"type": "string"}, "to": {"type": "string"}, + "lines": {"type": "array", "items": {"type": "string"}}}}}}} + + +def _hash(value: Any) -> str: + return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()[:16] + + +def _lines(legacy: Path, rel: str) -> list[str]: + try: + return (legacy / rel).read_text(errors="replace").splitlines() + except OSError: + return [] + + +def screen_id(rel: str, taken: set[str]) -> str: + """A screen's id from its file: the path without the usual view folders and the extension, in capitals.""" + p = PurePosixPath(rel) + parts = [x for x in p.with_suffix("").parts if x.lower() not in {"src", "main", "webapp", "web-inf", "jsp", "views", "templates", "pages", + "resources", "public", "app", "web"}] or [p.stem] + base = re.sub(r"[^A-Z0-9]+", "-", "-".join(parts[-3:]).upper()).strip("-") or "SCREEN" + name, n = base, 2 + while name in taken: + name, n = f"{base}-{n}", n + 1 + taken.add(name) + return name + + +def batches(views: list[str], legacy: Path) -> list[list[str]]: + out: list[list[str]] = [[]] + size = 0 + for v in views: + n = (legacy / v).stat().st_size if (legacy / v).is_file() else 0 + if out[-1] and (len(out[-1]) >= BATCH_FILES or size + n > BATCH_BYTES): + out.append([]) + size = 0 + out[-1].append(v) + size += n + return [b for b in out if b] + + +def screen_problems(answer: dict[str, Any] | None, batch: list[str], legacy: Path) -> list[str]: + if not answer or not isinstance(answer.get("files"), list): + return ["no answer"] + found, seen = [], set() + for f in answer["files"]: + name = f.get("file") + if name not in batch: + found.append(f"{name}: not a file of this batch") + continue + seen.add(name) + count = len(_lines(legacy, name)) + for what in ("fields", "actions"): + for item in f.get(what) or []: + if not 1 <= int(item.get("line") or 0) <= count: + found.append(f"{name}: {what[:-1]} {item.get('name') or item.get('label')!r} cites line {item.get('line')}, which {name} does not have ({count} lines)") + if not str(f.get("title") or "").strip(): + found.append(f"{name}: no title") + found += [f"{name}: missing from the answer" for name in batch if name not in seen] + return found + + +def _numbered(legacy: Path, rel: str) -> str: + return "\n".join(f"{n:5} {line}" for n, line in enumerate(_lines(legacy, rel), 1)) + + +def read_screens(folder, claude, legacy: Path, views: list[str], words: str, plan_only: bool = False) -> dict[str, Any]: + """D1 for any stack: the screens of the view files, in the inventory's shape, each made by a checked Claude step.""" + from reframe.claude.steps import stop_for + from reframe.claude.workspace import paths + from reframe.design import rounds + places = paths(folder) + project = folder.state["project"] + saved = folder.load(FILE, {}) or {} + kept, log = saved.get("screens") or {}, saved.get("log") or [] + todo, why, plan = [], [], {} + for i, batch in enumerate(batches(views, legacy), 1): + data = {"files": [{"file": v, "lines": _numbered(legacy, v)} for v in batch]} + key, digest = f"b{i}", _hash([data, METHOD]) + if (kept.get(key) or {}).get("hash") != digest or (kept.get(key) or {}).get("problems"): + todo.append((key, batch, data, digest)) + why.append((key, rounds.changed(kept.get(key), rounds.parts(data, METHOD)))) + plan = rounds.summary(why, [k for k in kept if k not in {t[0] for t in todo}]) + if plan_only: + return {"round": plan} + folder_in = places["analysis"] / "reframe" / "design" + folder_in.mkdir(parents=True, exist_ok=True) + for key, batch, data, digest in todo: + path = folder_in / f"reader-screens-{key}.json" + path.write_text(json.dumps(data, indent=1)) + prompt = SCREENS_PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", + languages=words) + answer, wrong = None, ["no answer"] + for attempt in (1, 2): + step = claude.run(f"reader-screens-{key}{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else + prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=SCREENS_SCHEMA) + log.append({"part": key, "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}}) + if not step.ok: + if step.problem in ("limit", "signin"): + folder.save(FILE, {**saved, "screens": kept, "log": log}) + raise stop_for(step, "the screens") + wrong = [f"the step did not finish ({step.problem})"] + continue + answer = claude.structured(step) + wrong = screen_problems(answer, batch, legacy) + if not wrong: + break + good = [] if wrong else (answer or {}).get("files") or [] + kept[key] = {"hash": digest, "parts": rounds.parts(data, METHOD), "files": batch, "answer": good, "problems": wrong} + folder.save(FILE, {**saved, "screens": kept, "log": log}) + taken: set[str] = set() + screens = [] + for key in sorted(kept, key=lambda k: int(k[1:])): + part = kept[key] + answered = {f["file"]: f for f in part["answer"]} + for rel in part["files"]: + if rel not in views: + continue + f = answered.get(rel) or {"title": "", "fields": [], "actions": []} + screens.append(as_screen(rel, f, screen_id(rel, taken), part["problems"])) + value = {"reader": "general", "screens": screens, "maps": len(screens), "mapsets": len(screens), "fields": sum(len(s["fields"]) for s in screens), + "problems": sum(len(s["problems"]) for s in screens), "steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)} + folder.save(FILE, {**(folder.load(FILE, {}) or {}), "screens": kept, "log": log}) + return {**value, "round": plan} + + +def as_screen(rel: str, answer: dict[str, Any], sid: str, problems: list[str]) -> dict[str, Any]: + """One view in the inventory's shape (reframe.design.inventory): fields, keys (its actions), programs and problems.""" + fields = [{"name": str(f.get("name") or ""), "kind": f.get("kind", "input"), "label": str(f.get("label") or ""), + "validation": str(f.get("validation") or ""), "line": int(f.get("line") or 0), "column": 1, "length": 0, + "attributes": [f["validation"]] if f.get("validation") else [], "color": "", "highlight": "", "initial": "", "picin": "", + "picout": "", "justify": "", "occurs": 0, "source_line": int(f.get("line") or 0)} for f in answer.get("fields") or []] + shown, seen = [], set() + for a in answer.get("actions") or []: + key = str(a.get("label") or a.get("target") or "action").strip()[:60] + if key in seen: + continue + seen.add(key) + shown.append({"key": key, "says": key, "kind": a.get("kind", ""), "target": str(a.get("target") or ""), "line": int(a.get("line") or 0)}) + return {"reader": "general", "mapset": sid, "map": sid, "title": str(answer.get("title") or "") or sid.replace("-", " ").title(), "file": rel, + "source_line": 1, "size": [0, 0], "symbolic": "", "programs": [{"name": rel, "file": rel}], "fields": fields, + "counts": {k: sum(1 for f in fields if f["kind"] == k) for k in ("input", "output", "label", "stopper")}, + "keys": {"shown": shown, "handled": [], "shown_not_handled": [], "handled_not_shown": []}, + "problems": [f"the reader's answer failed twice: {p}" for p in problems]} + + +# ---- D2: the flow ------------------------------------------------------------------------------------------------------ + +JAVA_CLASS_ROUTE = re.compile(r"@(?:RequestMapping|Path|UrlBinding)\(\s*(?:value\s*=\s*|path\s*=\s*)?\"([^\"]*)\"") +JAVA_METHOD_ROUTE = re.compile(r"@(?:GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping|Path)(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?\"([^\"]*)\")?") +RETURN_VIEW = re.compile(r"return\s+\"([^\":]+)\"\s*;") +REDIRECT = re.compile(r"\"redirect:([^\"?]+)|RedirectToAction\(\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?|header\(\s*'Location:\s*([^'?]+)|Location:\s*([^\"'?\s]+)") +HREF = re.compile(r"\b(href|action)\s*=\s*[\"']([^\"'#]+)") +ACTION_LINK = re.compile(r"Html\.ActionLink\(\s*\"[^\"]*\"\s*,\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?") # (text, action[, controller]) +BEGIN_FORM = re.compile(r"Html\.BeginForm\(\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?") # (action[, controller]) +CS_ACTION = re.compile(r"public\s+(?:async\s+)?(?:ActionResult|IActionResult|Task<\w+>|ViewResult)\s+(\w+)\s*\(") + + +def _clean(url: str) -> str: + url = re.sub(r"\$\{[^}]*\}|<%=?[^%]*%>|@\{[^}]*\}|~", "", url.strip()) + url = re.sub(r"/+", "/", url.split("?")[0].split("#")[0].strip()) + return "/" + url.strip("/") if url else "" + + +def routes(legacy: Path, files: list[str]) -> dict[str, dict[str, Any]]: + """Route -> {handler file, line, renders: [view names], redirects: [targets]}: read from the code with no model.""" + found: dict[str, dict[str, Any]] = {} + for rel in files: + lines = _lines(legacy, rel) + suffix = PurePosixPath(rel).suffix.lower() + if suffix in (".java", ".kt", ".groovy"): + text = "\n".join(lines) + base = "" + cls = re.search(r"^\s*(?:public\s+)?(?:final\s+)?class\s", text, re.M) + head = text[:cls.start()] if cls else "" + m = JAVA_CLASS_ROUTE.search(head) + if m: + base = _clean(m.group(1)) + for n, line in enumerate(lines, 1): + mm = JAVA_METHOD_ROUTE.search(line) + if mm and (not cls or n > text[:cls.start()].count("\n") + 1): + route = _clean(base + "/" + (mm.group(1) or "")) or base or "/" + body = "\n".join(lines[n:n + 40]) + body = body.split("@GetMapping")[0].split("@PostMapping")[0].split("@RequestMapping")[0] + found.setdefault(route, {"handler": rel, "line": n, "renders": [], "redirects": []}) + found[route]["renders"] += [v for v in RETURN_VIEW.findall(body)] + found[route]["redirects"] += [_clean(r[0]) for r in REDIRECT.findall(body) if r[0]] + elif suffix in (".cs", ".vb") and re.search(r"Controller\.(cs|vb)$", rel): + controller = re.sub(r"Controller\.(cs|vb)$", "", PurePosixPath(rel).name) + for n, line in enumerate(lines, 1): + m = CS_ACTION.search(line) + if not m: + continue + action = m.group(1) + body = "\n".join(lines[n:n + 40]) + nxt = CS_ACTION.search(body) + body = body[:nxt.start()] if nxt else body + route = f"/{controller}/{action}" + renders = [f"{controller}/{action}"] if re.search(r"\bView\((?!\s*\")", body) else [] # View() or View(model): the action's own view + renders += [f"{controller}/{v}" for v in re.findall(r"\bView\(\s*\"(\w+)\"", body)] + redirects = [f"/{(r[2] or controller)}/{r[1]}" for r in REDIRECT.findall(body) if r[1]] + found.setdefault(route, {"handler": rel, "line": n, "renders": [], "redirects": []}) + found[route]["renders"] += renders + found[route]["redirects"] += redirects + if action == "Index": + found.setdefault(f"/{controller}", found[route]) + elif suffix in (".php", ".asp", ".pl", ".cgi", ".rb", ".py") or (suffix in (".jsp", ".html", ".htm") and "WEB-INF/" not in rel): # a page at its own path + redirects = [_clean(r[3] or r[4]) for r in REDIRECT.findall("\n".join(lines)) if (r[3] or r[4])] + found.setdefault("/" + rel, {"handler": rel, "line": 1, "renders": [rel] if suffix != ".py" else [], "redirects": redirects}) + return found + + +def resolve_view(name: str, views: dict[str, str]) -> str | None: + """A view name (`orders/list`, `Orders/Index`, or a page's path) -> the screen id whose file it names.""" + name = name.strip("/").lower() + if not name: + return None + for rel, sid in views.items(): + stem = PurePosixPath(rel).with_suffix("").as_posix().lower() + if rel.lower() == name or stem.endswith("/" + name) or stem == name: + return sid + return None + + +def used_files(legacy: Path, rel: str, stems: dict[str, list[str]]) -> list[str]: + """The codebase's own files a handler uses, one level deep: the classes it names whose file is in the source.""" + text = "\n".join(_lines(legacy, rel)) + names = set(re.findall(r"\b([A-Z][A-Za-z0-9_]{2,})\b", text)) + return sorted({f for n in names for f in stems.get(n, []) if f != rel}) + + +def read_flow(folder, claude, legacy: Path, screens: dict[str, Any], stack: dict[str, Any], plan_only: bool = False) -> dict[str, Any]: + """D2 for any stack: the links between screens, by pattern where one settles it and by a checked Claude step for the rest. + The ends of a link are view files and routes; each route stands for the screens it renders, or those it redirects to.""" + from reframe.source import profile + views = {s["file"]: s["map"] for s in screens["screens"]} + code = sorted({p.relative_to(legacy).as_posix() for p in legacy.rglob("*") if p.is_file() + and not profile.is_library(p.relative_to(legacy).as_posix()) + and profile.language(p.relative_to(legacy).as_posix(), p.read_bytes()[:4096]) not in (None, "SQL")}) + stems: dict[str, list[str]] = defaultdict(list) + for rel in code: + stems[PurePosixPath(rel).stem].append(rel) + table = routes(legacy, code) + screens_of: dict[str, set[str]] = defaultdict(set) + for rel, sid in views.items(): + screens_of[rel].add(sid) + links: list[dict[str, Any]] = [] + unsettled: list[dict[str, Any]] = [] + keys: list[dict[str, Any]] = [] + + def target_of(raw: str, where: str) -> str | None: + """A link as written -> a route Reframe knows, or a view file.""" + url = _clean(raw) + relative = "/" + (PurePosixPath(where).parent / raw.split("?")[0]).as_posix().lstrip("/") if raw and not raw.startswith("/") else url + for candidate in (url, relative): + if candidate in table: + return candidate + sid = resolve_view(url, views) or resolve_view(relative, views) + return next(rel for rel, s in views.items() if s == sid) if sid else None + + for route, r in table.items(): + for v in r["renders"]: + sid = resolve_view(v, views) + if sid: + screens_of[route].add(sid) + links.append({"kind": "renders", "from": route, "to": next(rel for rel, x in views.items() if x == sid), + "lines": [f"{r['handler']}:{r['line']}"], "how": "pattern"}) + for red in r["redirects"]: + to = target_of(red, r["handler"]) + link = {"kind": "redirect", "from": route, "to": to or red, "lines": [f"{r['handler']}:{r['line']}"], "how": "pattern"} + (links if to else unsettled).append(link) + for _ in range(3): # a route that renders nothing stands for the screens its redirects reach + for link in links: + if link["kind"] == "redirect" and not any(x["kind"] == "renders" and x["from"] == link["from"] for x in links): + screens_of[link["from"]] |= screens_of.get(link["to"], set()) + for s in screens["screens"]: + rel = s["file"] + targets: dict[str, list[str]] = defaultdict(list) + for n, line in enumerate(_lines(legacy, rel), 1): + found = [("form" if kind == "action" else "href", raw) for kind, raw in HREF.findall(line) + if not raw.startswith(("http:", "https:", "mailto:", "javascript:")) and not re.search(r"\.(css|js|png|jpe?g|gif|svg|ico)$", raw)] + for kind, pattern in (("href", ACTION_LINK), ("form", BEGIN_FORM)): + for m in pattern.finditer(line): + found.append((kind, f"/{m.group(2) or PurePosixPath(rel).parent.name}/{m.group(1)}")) + for kind, raw in found: + to = target_of(raw, rel) + link = {"kind": kind, "from": rel, "to": to or raw, "lines": [f"{rel}:{n}"], "how": "pattern"} + (links if to else unsettled).append(link) + if to: + targets[raw].append(to) + targets[raw.rsplit("/", 1)[-1]].append(to) + for k in s["keys"]["shown"]: + written = str(k.get("target") or "") + direct = target_of(written, rel) if written else None + leads = list(targets.get(written) or ([direct] if direct else [])) + keys.append({"screen": s["map"], "key": k["key"], "to": sorted(set(leads))}) + resolved, unresolved = settle(folder, claude, legacy, unsettled, views, table, stack, plan_only) + links += resolved + for s in screens["screens"]: # the code behind a screen: the handlers that render it and what they use + handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table}) + used = sorted({f for h in handlers for f in used_files(legacy, h, stems)}) + s["programs"] = [{"name": p, "file": p} for p in dict.fromkeys([s["file"], *handlers, *used])] + reached = {sid for link in links if link["kind"] != "renders" for sid in screens_of.get(link["to"], set())} + entries = {sid for r in ("/", "/index.php", "/index.html", "/index.jsp") for sid in screens_of.get(r, set())} + reach = [{"screen": s["map"], "reached": "navigated" if s["map"] in reached else "entry" if s["map"] in entries else "unreached"} + for s in screens["screens"]] + return {"reader": "general", "links": links, "keys": keys, "reach": reach, "unresolved": unresolved, "transactions": [], + "routes": {k: {"handler": v["handler"], "line": v["line"]} for k, v in sorted(table.items())}, + "screens_of_programs": {k: sorted(v) for k, v in screens_of.items() if v}, + "counts": {"by_pattern": sum(1 for x in links if x.get("how") == "pattern"), "by_model": sum(1 for x in links if x.get("how") == "model"), + "unresolved": len(unresolved)}} + + +def link_problems(answer: dict[str, Any] | None, asked: list[dict[str, Any]], legacy: Path, views: dict[str, str], table: dict[str, Any]) -> list[str]: + if not answer or not isinstance(answer.get("links"), list): + return ["no answer"] + from reframe.reconcile.decide import missing_evidence + known, found, seen = {a["id"] for a in asked}, [], set() + for x in answer["links"]: + if x.get("id") not in known: + found.append(f"{x.get('id')}: not a link listed") + continue + seen.add(x["id"]) + to = str(x.get("to") or "") + if to and to not in views.values() and to not in table and not (legacy / to).is_file(): + found.append(f"{x['id']}: {to!r} is not a screen, a route or a file in the source") + bad = missing_evidence([str(c) for c in x.get("lines") or []], legacy) + if bad: + found.append(f"{x['id']}: lines that do not exist: {', '.join(bad)}") + found += [f"{i}: missing from the answer" for i in sorted(known - seen)] + return found + + +def settle(folder, claude, legacy: Path, unsettled: list[dict[str, Any]], views: dict[str, str], table: dict[str, Any], stack: dict[str, Any], + plan_only: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """The links no pattern settled, by one checked Claude step; asked again once, then left unresolved.""" + from reframe.claude.steps import stop_for + from reframe.claude.workspace import paths + if not unsettled or plan_only or claude is None: + return [], [{**x, "why": "no pattern settles it"} for x in unsettled] + asked = [{"id": f"L{n:03d}", "from": x["from"], "written": x["to"], "kind": x["kind"], "lines": x["lines"]} for n, x in enumerate(unsettled, 1)] + data = {"links": asked, "screens": [{"id": sid, "file": rel} for rel, sid in views.items()], "routes": sorted(table)} + saved = folder.load(FILE, {}) or {} + digest = _hash([data, METHOD]) + before = saved.get("links") or {} + if before.get("hash") == digest and not before.get("problems"): + answer, wrong = before.get("answer"), [] + else: + places, project = paths(folder), folder.state["project"] + folder_in = places["analysis"] / "reframe" / "design" + folder_in.mkdir(parents=True, exist_ok=True) + path = folder_in / "reader-links.json" + path.write_text(json.dumps(data, indent=1)) + prompt = LINKS_PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", + languages=stack["words"]["languages"]) + answer, wrong = None, ["no answer"] + log = saved.get("log") or [] + for attempt in (1, 2): + step = claude.run(f"reader-links{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else + prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=LINKS_SCHEMA) + log.append({"part": "links", "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}}) + if not step.ok: + if step.problem in ("limit", "signin"): + folder.save(FILE, {**saved, "log": log}) + raise stop_for(step, "the screen flow") + wrong = [f"the step did not finish ({step.problem})"] + continue + answer = claude.structured(step) + wrong = link_problems(answer, asked, legacy, views, table) + if not wrong: + break + folder.save(FILE, {**(folder.load(FILE, {}) or {}), "links": {"hash": digest, "answer": answer if not wrong else None, "problems": wrong}, "log": log}) + if wrong: + return [], [{**x, "why": "; ".join(wrong)} for x in unsettled] + by_id = {x["id"]: x for x in (answer or {}).get("links") or []} + resolved, unresolved = [], [] + sid_file = {sid: rel for rel, sid in views.items()} + for a, x in zip(asked, unsettled): + got = by_id.get(a["id"]) or {} + to = str(got.get("to") or "") + if not to: + unresolved.append({**x, "why": "the source cannot show where it leads"}) + continue + to = sid_file.get(to) or to + resolved.append({**x, "to": to, "lines": x["lines"] + [c for c in got.get("lines") or [] if c not in x["lines"]], "how": "model"}) + return resolved, unresolved + + +def check(found: dict[str, Any], legacy: Path) -> list[str]: + """Every link's lines exist and it joins two things that exist (as reframe.design.flow.check does for the mainframe).""" + from reframe.reconcile.decide import missing_evidence + problems = [] + for link in found["links"]: + bad = missing_evidence(link["lines"], legacy) + if bad: + problems.append(f"{link['kind']} {link['from']} -> {link['to']}: lines that do not exist: {', '.join(bad)}") + for end in (link["from"], link["to"]): + if end not in found.get("routes", {}) and not (legacy / end).is_file(): + problems.append(f"{link['kind']} {link['from']} -> {link['to']}: {end} is not a route or a file in the source") + return problems diff --git a/src/reframe/design/journeys.py b/src/reframe/design/journeys.py index ccbddc2a..dbc7a86c 100644 --- a/src/reframe/design/journeys.py +++ b/src/reframe/design/journeys.py @@ -89,7 +89,7 @@ def screen_brief(s: dict[str, Any], full: bool) -> dict[str, Any]: def label_for(f): near = [t for (line, end), t in labels.items() if line == f["line"] and end <= f["column"] + 2 and t] return near[-1] if near else "" - brief["inputs"] = [{"field": f["name"], "label": label_for(f), "length": f["length"]} for f in s["fields"] if f["kind"] == "input"] + brief["inputs"] = [{"field": f["name"], "label": f.get("label") or label_for(f), "length": f["length"]} for f in s["fields"] if f["kind"] == "input"] brief["shows"] = [f["name"] for f in s["fields"] if f["kind"] == "output"][:60] brief["keys"] = [{"key": k["key"], "says": k["says"]} for k in s["keys"]["shown"]] return brief @@ -225,7 +225,8 @@ def one(item) -> None: safe = "".join(c if c.isalnum() else "-" for c in (key or "no-domain")).strip("-")[:50] path = folder_in / f"journeys-{safe}.json" path.write_text(json.dumps(data, indent=1)) - prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") + from reframe.source import profile + prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") answer, wrong, attempts = None, ["no answer"], 0 for attempt in (1, 2): attempts = attempt diff --git a/src/reframe/design/legacy.py b/src/reframe/design/legacy.py index f25c28da..1cace778 100644 --- a/src/reframe/design/legacy.py +++ b/src/reframe/design/legacy.py @@ -45,7 +45,14 @@ def _color(f: dict[str, Any]) -> str: def grid(screen: dict[str, Any]) -> str: - """The screen as
     text, a span per run of cells of one field."""
    +    """The screen as 
     text, a span per run of cells of one field. A screen the general reader read (L1-05) has no
    +    3270 layout: it is shown as its field list, one line per field and action, citing the view's lines."""
    +    if screen.get("reader") == "general":
    +        rows = [f"{html.escape((f.get('label') or f['name'])[:40]):40} {'[' + html.escape(f['name']) + ']' if f['kind'] == 'input' else '<' + html.escape(f['name']) + '>'}"
    +                + (f"  ({html.escape(f['validation'])})" if f.get("validation") else "") + f"  line {f['line']}" for f in screen["fields"]]
    +        rows += [f"{'(' + html.escape(k.get('kind') or 'action') + ')':40} {html.escape(k['says'])}" + (f"  → {html.escape(k['target'])}" if k.get("target") else "")
    +                 for k in screen["keys"]["shown"]]
    +        return "
    " + "\n".join(rows or ["(no fields or actions found)"]) + "
    " lines, columns = screen["size"] chars = [[" "] * columns for _ in range(lines)] owner: list[list[int | None]] = [[None] * columns for _ in range(lines)] @@ -116,7 +123,29 @@ def _fields(screen: dict[str, Any]) -> str: "Initial textBMS line" + "".join(rows) + "") +def general_page(screen: dict[str, Any], project: str) -> str: + """A screen the general reader read (L1-05): its fields and actions with the lines they are on, and its source file.""" + programs = ", ".join(f"{html.escape(p['name'])}" for p in screen["programs"]) + problems = "".join(f'
  • {html.escape(p)}
  • ' for p in screen["problems"]) or '
  • None.
  • ' + fields = "".join(f"{html.escape(f['name'] or '–')}{html.escape(f.get('label') or '')}{f['kind']}" + f"{html.escape(f.get('validation') or '')}{f['line']}" for f in screen["fields"]) + actions = "".join(f"{html.escape(k['says'])}{html.escape(k.get('kind') or '')}{html.escape(k.get('target') or '')}" + f"{k.get('line') or ''}" for k in screen["keys"]["shown"]) + return f""" +{html.escape(screen['map'])} legacy screen
    +

    All legacy screens · {html.escape(project)}

    +

    {html.escape(screen['title'] or screen['map'])}

    +

    Screen {html.escape(screen['map'])}, from the legacy source file {html.escape(screen['file'])} · the code behind it: {programs}

    +

    Read by Reframe's general reader: the fields and actions by a Claude step whose every cited line Reframe checked. Model output, for review. The old page is not drawn.

    +

    Fields

    {fields or ''}
    FieldLabelKindValidationLine
    None found.
    +

    Actions

    {actions or ''}
    ActionKindGoes to, as writtenLine
    None found.
    +

    Checks

      {problems}
    +
    """ + + def page(screen: dict[str, Any], project: str) -> str: + if screen.get("reader") == "general": + return general_page(screen, project) title = screen["title"] or screen["map"] c = screen["counts"] programs = ", ".join(f"{html.escape(p['name'])}" for p in screen["programs"]) or 'none found' @@ -136,6 +165,9 @@ def page(screen: dict[str, Any], project: str) -> str: def index(found: dict[str, Any], project: str) -> str: + how = (f"{found['maps']} screens, {found['fields']} fields, read from the views by Reframe's general reader (a checked Claude step)." + if found.get("reader") == "general" else + f"{found['maps']} maps in {found['mapsets']} mapsets, {found['fields']} fields, read from the BMS source with no model.") rows = [] for s in found["screens"]: keys = s["keys"] @@ -146,7 +178,7 @@ def index(found: dict[str, Any], project: str) -> str: return f""" Legacy screens

    Legacy screens

    -

    {html.escape(project)} · {found['maps']} maps in {found['mapsets']} mapsets, {found['fields']} fields, read from the BMS source with no model. +

    {html.escape(project)} · {how} {found['problems']} check problem(s).

    {''.join(rows)}
    ScreenMapProgramsInputsOutputsKeys that differProblems
    """ diff --git a/src/reframe/design/pipeline.py b/src/reframe/design/pipeline.py index 3d17a206..44a399ed 100644 --- a/src/reframe/design/pipeline.py +++ b/src/reframe/design/pipeline.py @@ -288,11 +288,24 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p return report folder.update(design={**state, "round": number, "status": "running", "context": str(context) if context else "", "started_at": iso()}) legacy_folder = paths(folder)["legacy"] - found = inventory.inventory(legacy_folder) - folder.save("design/screens.json", found) + stack_profile = profile.of_run(folder) + if stack_profile.get("family", "mainframe") == "mainframe": # the exact readers: BMS maps and CICS, with no model + found = inventory.inventory(legacy_folder) + folder.save("design/screens.json", found) + linked = flow.flow(legacy_folder, found) + linked["problems"] = flow.check(linked, legacy_folder) + else: # the general reader (L1-05): fields and actions by a checked Claude step; links by pattern, then a checked step + from reframe.design import general + views = profile.files_with(legacy_folder, "ui") + found = general.read_screens(folder, claude, legacy_folder, views, stack_profile["words"]["languages"]) if views else \ + {"reader": "general", "screens": [], "maps": 0, "mapsets": 0, "fields": 0, "problems": 0} + linked = general.read_flow(folder, claude, legacy_folder, found, stack_profile) + linked["problems"] = general.check(linked, legacy_folder) + found.pop("round", None) + folder.save("design/screens.json", found) + report["reader"] = {"screens": found.get("steps", 0), "links": linked["counts"]} + left_out = without_screens(stack_profile, found) legacy.draw_all(folder, found) - linked = flow.flow(legacy_folder, found) - linked["problems"] = flow.check(linked, legacy_folder) folder.save("design/flow.json", linked) flowpage.draw(folder, found, linked) if left_out: # a batch system, a service or a library: no journeys, modern screens or prototype, and the page says why diff --git a/src/reframe/design/screens.py b/src/reframe/design/screens.py index daec4e3a..4fb9c04d 100644 --- a/src/reframe/design/screens.py +++ b/src/reframe/design/screens.py @@ -328,7 +328,8 @@ def one(item, across: list[str] | None = None) -> None: safe = "".join(c if c.isalnum() else "-" for c in (key or "no-domain")).strip("-")[:50] path = folder_in / f"screens-{safe}{'-links' if across else ''}.json" path.write_text(json.dumps(data, indent=1)) - prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") + from reframe.source import profile + prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") answer, wrong, attempts = None, across or ["no answer"], 0 for attempt in ((3,) if across else (1, 2)): # the links pass: one more ask, with every other domain's screens attempts = attempt diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index 4ed7b603..958a7368 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -444,7 +444,8 @@ def one(item) -> None: safe = slug(name)[:50] + "-" + hashlib.sha256(name.encode()).hexdigest()[:6] # unique: batches of one function share a long name path = folder_in / f"specs-{safe}.json" path.write_text(json.dumps(data, indent=1)) - prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") + from reframe.source import profile + prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}") answer, wrong, attempts = None, ["no answer"], 0 for attempt in (1, 2): attempts = attempt diff --git a/src/reframe/source/profile.py b/src/reframe/source/profile.py index 1703f127..78d06b2a 100644 --- a/src/reframe/source/profile.py +++ b/src/reframe/source/profile.py @@ -170,6 +170,18 @@ def _joined(names: list[str]) -> str: return " and ".join(names) if names else "the source" +def files_with(root: Path, what: str) -> list[str]: + """Every file under root that shows `what` (ui, routes, jobs or data), in name order; the profile records a sample.""" + rules = {"ui": UI, "routes": ROUTES, "jobs": JOBS, "data": DATA}[what] + found = [] + for p in sorted(root.rglob("*")): + if p.is_file() and not p.is_symlink(): + rel = p.relative_to(root).as_posix() + if not is_library(rel) and _matches(rules, rel, p.read_bytes()[:READ].decode("utf-8", errors="replace")): + found.append(rel) + return found + + def profile_archive(archive: Path, told: str | None = None) -> dict[str, Any]: members = [] with zipfile.ZipFile(archive) as z: @@ -224,7 +236,25 @@ def in_words(text: str, stack: dict[str, Any]) -> str: if stack.get("family", "mainframe") == "mainframe": return text words = stack["words"] + for mainframe, other in DESIGN_WORDS: + text = text.replace(mainframe, other) return (text.replace("a PERFORM, CALL or copybook", words["follow"]) .replace("who do not read COBOL", f"who do not read {words['languages']}") .replace(MAINFRAME_REACH, OTHER_REACH) .replace("from programs of a legacy system", "from the source files of a legacy system")) + + +DESIGN_WORDS = [ + ("a legacy mainframe application", "a legacy application"), + ("the domain's 3270 screens (fields and function keys)", "the domain's screens (fields and actions)"), + ("which screen leads to which, by key, menu option or transfer", "which screen leads to which, by link, form or redirect"), + ('"screen" (the map name, exactly as listed, such as COSGN0A)', '"screen" (the screen id, exactly as listed)'), + ("its 3270 screens (each data field with its label, length and attributes, and each function key with where it leads)", + "its screens (each data field with its label and validation, and each action with where it leads)"), + ("Do not recreate poor 3270 usability", "Do not recreate poor legacy usability"), + ('the legacy screens it "replaces" (map names)', 'the legacy screens it "replaces" (their screen ids)'), + ('every function key (kind "key", such as F3)', 'every action (kind "key", its label exactly as listed)'), + ("The header fields every legacy screen repeats (transaction, program, date, time, titles)", "The header and navigation every legacy page repeats"), + ("without the mainframe mechanics (VSAM, CICS, JCL, COMMAREA)", "without the legacy framework's mechanics (sessions, configuration, the old libraries)"), +] +"""The design's prompts (journeys, modern screens, specifications), written for the mainframe, in any other stack's words (L1-05).""" diff --git a/tests/design/test_general.py b/tests/design/test_general.py new file mode 100644 index 00000000..6fb9d3ba --- /dev/null +++ b/tests/design/test_general.py @@ -0,0 +1,228 @@ +"""L1-05: screens and flow from any stack (docs/any-legacy.md, section 5.4). The general reader lists each view's fields +and actions, and the routes and links between them, each citing lines and checked; patterns that settle a link need no +model; what fails twice is unresolved. The journeys, modern screens and prototype then work as on the mainframe.""" +import os +import re +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from reframe.core.runfolder import new_run +from reframe.design import general, pipeline +from reframe.source import profile +from tests import stacks +from tests.design.test_specs import written +from tests.reconcile.test_decide import FakeClaude + +FIELD = re.compile(r"]*\bname=\"(\w+)\"[^>]*>|TextBoxFor\(m => m\.(\w+)") +ACTION = re.compile(r"]*>([^<]+)|([^<]+)|ActionLink\(\"([^\"]+)\", \"(\w+)\"") + + +def read_views(data): + """What the reader's step answers: the fields and actions of each view, with the lines they are on.""" + files = [] + for f in data["files"]: + fields, actions = [], [] + for row in f["lines"].splitlines(): + n, _, line = row.strip().partition(" ") + for m in FIELD.finditer(line): + name = m.group(1) or m.group(2) + fields.append({"name": name, "label": name.title(), "kind": "input", "validation": "required" if "required" in line else "", "line": int(n)}) + for m in ACTION.finditer(line): + if m.group(1): + actions.append({"label": m.group(1).strip(), "kind": "submit", "target": "", "line": int(n)}) + else: + actions.append({"label": m.group(3) or m.group(4), "kind": "link", "target": m.group(2) or m.group(5), "line": int(n)}) + files.append({"file": f["file"], "title": Path(f["file"]).stem.title(), "fields": fields, "actions": actions}) + return {"files": files} + + +def wrong_lines(data): + answer = read_views(data) + for f in answer["files"]: + for x in f["fields"]: + x["line"] = 999 + return answer + + +def journeys_for(data): + screens = [s["screen"] for s in data["screens"]] + return {"journeys": [{"name": f"Work with {data['domain']['name']}", "role": "user", "goal": "Get it done", + "steps": [{"screen": s, "action": "Use it"} for s in screens], + "capabilities": [c["key"] for c in data["capabilities"]], + "requirements": [c["requirements"][0]["key"] for c in data["capabilities"] if c["requirements"]]}] if screens else [], + "unused": []} + + +def safe(text): + return re.sub(r"[^A-Za-z0-9]+", "-", text).strip("-") + + +def screens_for(data): + found, mapping = [], [] + for s in data["legacy_screens"]: + sid = f"S-{s['screen']}" + parts = [{"id": f"f-{safe(f['field'])}", "type": "text", "label": f["label"] or f["field"]} for f in s["fields"]] + parts += [{"id": f"k-{safe(k['key'])}", "type": "button", "label": k["says"] or k["key"]} for k in s["keys"]] + if parts: + parts[0]["rules"] = [r["key"] for r in data["rules"] if r["kind"] == "validation" and r["program"] in s["programs"]] + found.append({"id": sid, "title": s["title"], "purpose": "p", "journeys": [j["id"] for j in data["journeys"]][:1], "replaces": [s["screen"]], + "components": parts or [{"id": "c-page", "type": "text", "label": s["title"]}]}) + mapping.append({"legacy_screen": s["screen"], "legacy": s["screen"], "kind": "screen", "how": "kept", "becomes": sid, "why": "w"}) + mapping += [{"legacy_screen": s["screen"], "legacy": f["field"], "kind": "field", "how": "kept", "becomes": f"{sid}/f-{safe(f['field'])}", "why": "w"} + for f in s["fields"]] + mapping += [{"legacy_screen": s["screen"], "legacy": k["key"], "kind": "key", "how": "kept", "becomes": f"{sid}/k-{safe(k['key'])}", "why": "w"} + for k in s["keys"]] + return {"screens": found, "mapping": mapping} + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name}) + env.start() + self.addCleanup(env.stop) + + def run_for(self, name, reader=read_views): + self.folder = new_run(name.replace("-", "")) + self.folder.update(project="shop", tools="claude") + self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", stacks.FIXTURES[name]) + self.stack = profile.profile_folder(self.legacy) + self.folder.save(profile.FILE, self.stack) + self.claude = FakeClaude(reader=reader, journeys=journeys_for, screens=screens_for, specs=written) + self.claude.root = self.folder.root / "claude" + views = profile.files_with(self.legacy, "ui") + found = general.read_screens(self.folder, self.claude, self.legacy, views, self.stack["words"]["languages"]) + linked = general.read_flow(self.folder, self.claude, self.legacy, found, self.stack) + return found, linked + + +class ReaderTest(Base): + def test_java_screens_fields_and_actions_each_citing_its_line(self): + found, _ = self.run_for("java") + by = {s["map"]: s for s in found["screens"]} + self.assertEqual(sorted(by), ["ORDERS-LIST", "ORDERS-NEW"]) + form = by["ORDERS-NEW"] + self.assertEqual([(f["name"], f["kind"], f["validation"], f["line"]) for f in form["fields"]], + [("customer", "input", "required", 4), ("quantity", "input", "", 5)]) + self.assertEqual([k["key"] for k in form["keys"]["shown"]], ["Place order", "Back"]) + self.assertEqual(found["steps"], 1) # one batch of view files, one step + self.assertEqual([c[0] for c in self.claude.other_calls], ["reader-screens-b1"]) + + def test_java_links_by_pattern_with_no_model(self): + found, linked = self.run_for("java") + links = {(x["kind"], x["from"], x["to"]) for x in linked["links"]} + jsp = "src/main/webapp/WEB-INF/jsp/orders/" + self.assertIn(("href", jsp + "list.jsp", "/orders/new"), links) # an href to a route + self.assertIn(("renders", "/orders/new", jsp + "new.jsp"), links) # the route's handler returns "orders/new" + self.assertIn(("form", jsp + "new.jsp", "/orders/new"), links) # the form's action + self.assertIn(("redirect", "/orders/new", "/orders"), links) # "redirect:/orders" + self.assertEqual(linked["counts"]["by_model"], 0) + self.assertEqual(linked["unresolved"], []) + self.assertEqual(general.check(linked, self.legacy), []) # every line exists, every end is a route or a file + self.assertEqual(linked["screens_of_programs"]["/orders"], ["ORDERS-LIST"]) + self.assertEqual({r["screen"]: r["reached"] for r in linked["reach"]}, {"ORDERS-LIST": "navigated", "ORDERS-NEW": "navigated"}) + new = next(s for s in found["screens"] if s["map"] == "ORDERS-NEW") # the code behind the form: its controller and the service it uses + self.assertEqual([p["name"] for p in new["programs"]], [jsp + "new.jsp", "src/main/java/org/demo/shop/web/OrderController.java", + "src/main/java/org/demo/shop/model/Order.java", + "src/main/java/org/demo/shop/service/OrderService.java"]) + keys = {(k["screen"], k["key"]): k["to"] for k in linked["keys"]} + self.assertEqual(keys[("ORDERS-NEW", "Back")], ["/orders"]) + + def test_dotnet_by_its_conventions(self): + found, linked = self.run_for("dotnet") + self.assertEqual(sorted(s["map"] for s in found["screens"]), ["SHOP-ORDERS-CREATE", "SHOP-ORDERS-INDEX"]) + links = {(x["kind"], x["from"], x["to"]) for x in linked["links"]} + self.assertIn(("renders", "/Orders/Index", "Shop/Views/Orders/Index.cshtml"), links) # View() renders Views/Orders/Index + self.assertIn(("href", "Shop/Views/Orders/Index.cshtml", "/Orders/Create"), links) # Html.ActionLink("New order", "Create") + self.assertIn(("redirect", "/Orders/Create", "/Orders/Index"), links) # RedirectToAction("Index") + self.assertEqual(general.check(linked, self.legacy), []) + + def test_php_pages_and_a_redirect(self): + found, linked = self.run_for("web-script") + self.assertEqual([s["map"] for s in found["screens"]], ["INDEX"]) + links = {(x["kind"], x["from"], x["to"]) for x in linked["links"]} + self.assertIn(("form", "index.php", "/orders.php"), links) + self.assertIn(("redirect", "/orders.php", "/index.php"), links) # header('Location: index.php') + self.assertEqual(linked["screens_of_programs"]["/orders.php"], ["INDEX"]) # a handler that renders nothing leads where it redirects + + def test_an_answer_that_fails_twice_is_kept_unresolved_never_guessed(self): + found, _ = self.run_for("java", reader=wrong_lines) + self.assertEqual([c[0] for c in self.claude.other_calls], ["reader-screens-b1", "reader-screens-b1-retry"]) + retry = self.claude.other_calls[1][2] + self.assertIn("does not have", retry) # asked again with the reasons + self.assertTrue(all(s["fields"] == [] and s["problems"] for s in found["screens"])) + + def test_a_link_no_pattern_settles_goes_to_a_checked_step(self): + self.folder = new_run("shopx") + self.folder.update(project="shop", tools="claude") + files = {**stacks.JAVA_WEB, "src/main/webapp/WEB-INF/jsp/orders/list.jsp": stacks.JAVA_WEB["src/main/webapp/WEB-INF/jsp/orders/list.jsp"] + .replace('', '')} + self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", files) + stack = profile.profile_folder(self.legacy) + answers = [] + + def reader(data): + if "links" in data: + answers.append(data) + return {"links": [{"id": x["id"], "to": "ORDERS-NEW", "lines": [x["lines"][0]]} for x in data["links"]]} + return read_views(data) + + claude = FakeClaude(reader=reader) + claude.root = self.folder.root / "claude" + found = general.read_screens(self.folder, claude, self.legacy, profile.files_with(self.legacy, "ui"), "Java and JSP") + linked = general.read_flow(self.folder, claude, self.legacy, found, stack) + self.assertEqual([x["written"] for x in answers[0]["links"]], ["${ctx}/legacy/start.do"]) + model = [x for x in linked["links"] if x["how"] == "model"] + self.assertEqual([(x["from"], x["to"]) for x in model], [("src/main/webapp/WEB-INF/jsp/orders/list.jsp", "src/main/webapp/WEB-INF/jsp/orders/new.jsp")]) + self.assertEqual(linked["counts"]["by_model"], 1) + + +class WordsTest(unittest.TestCase): + def test_the_designs_prompts_in_the_stacks_words(self): + from reframe.design import journeys, screens, specs + java = {"family": "java", "words": {"languages": "Java and JSP", "follow": "a call", "program": "source file"}} + for name, text in (("journeys", journeys.PROMPT), ("screens", screens.PROMPT), ("specs", specs.PROMPT)): + self.assertIs(profile.in_words(text, {"family": "mainframe"}), text, name) # the mainframe's prompts are as before + out = profile.in_words(text, java) + for word in ("3270", "mainframe", "F3", "COSGN0A", "function key", "VSAM", "map name"): + self.assertNotIn(word, out, name) + + +class RoundTest(Base): + """A whole design round on the Java fixture: the journeys, modern screens, prototype and specifications work from the + screens and flow the general reader gives them.""" + + def test_a_design_round_on_java(self): + self.run_for("java") + fee = "rec/u:order/1" + self.folder.save("outputs/reconcile/rules.json", {"rules": [{ + "key": fee, "program": "src/main/java/org/demo/shop/service/OrderService.java", "function": "Orders/Place", "kind": "validation", + "name": "Customer required", "confidence": "high", "text": "WHEN no customer is given, THE order SHALL be refused with 'A customer is required'", + "covers": ["u/c"], "evidence": ["src/main/java/org/demo/shop/service/OrderService.java:20"], "entry": [], "examples": []}]}) + self.folder.save("outputs/reconcile/requirements.json", {"complete": True, "domains": [{"key": "orders", "name": "Orders", "functions": ["Orders/Place"]}], + "names": {"Orders/Place": {"name": "Place orders"}}, + "functions": {"Orders/Place": {"capabilities": [{ + "number": 1, "title": "Place an order", "story": "As a customer, I want to order", "risk": "", + "touches": [], "questions": [], "tables": [], + "requirements": [{"code": "REQ-F-001", "kind": "functional", "pattern": "unwanted behaviour", + "rules": [fee], "text": "If no customer is given, then the system shall refuse the order."}]}]}}}) + self.folder.save("reconcile/questions.json", {"questions": []}) + self.folder.save("snapshot.json", {"sha256": "abc"}) + value = pipeline.run(self.folder, self.claude) + self.assertEqual(value["reader"]["links"]["unresolved"], 0) + modern = self.folder.load("design/modern.json") + self.assertEqual(sorted(s["id"] for s in modern["screens"]), ["S-ORDERS-LIST", "S-ORDERS-NEW"]) + journeys = self.folder.load("design/journeys.json")["journeys"] + self.assertEqual(journeys[0]["domain"], "orders") # the screens reach the domain through their controller's service + self.assertTrue(self.folder.path("outputs/design/prototype/index.html").is_file()) + self.assertIn("general reader", self.folder.path("outputs/design/legacy/index.html").read_text()) + self.assertIn("Customer", self.folder.path("outputs/design/legacy/ORDERS-NEW.html").read_text()) + self.assertIn("Read by Reframe's general reader", self.folder.path("outputs/design/flow.html").read_text()) + self.assertIn("general reader", self.folder.path("outputs/design/index.html").read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/source/test_profile.py b/tests/source/test_profile.py index 940e4693..29183ccb 100644 --- a/tests/source/test_profile.py +++ b/tests/source/test_profile.py @@ -99,7 +99,7 @@ def test_recorded_after_the_snapshot_shown_by_status_and_the_reports(self): with mock.patch.object(commands, "find_run", return_value=self.folder), contextlib.redirect_stdout(out): commands.status(type("Args", (), {"run": None})()) self.assertIn("Stack", out.getvalue()) - self.assertIn("mixed: Java 4 files, C# 4 files, PHP 2 files; ui 1, routes 3, jobs 1, data 3", out.getvalue().replace("\n", "")) + self.assertIn("mixed: C# 4 files, Java 3 files, PHP 2 files; ui 1, routes 2, jobs 1, data 3", out.getvalue().replace("\n", "")) self.assertNotIn("Package check", out.getvalue()) # what AWS Transform makes of it matters for mainframe code only self.assertEqual(build._stack(self.folder), profile.summary(found)) self.assertEqual(build._package(self.folder), {}) diff --git a/tests/stacks.py b/tests/stacks.py index feadbf14..e6ba356f 100644 --- a/tests/stacks.py +++ b/tests/stacks.py @@ -30,6 +30,11 @@ return "orders/list"; } + @GetMapping("/new") + public String form() { + return "orders/new"; + } + @PostMapping("/new") public String create(@RequestParam String customer, @RequestParam int quantity) { if (quantity <= 0) { @@ -295,7 +300,7 @@ MAINFRAME = {"app/bms/SIGN00.bms": bms("SIGN00", "SIGN0A", "ENTER=Sign-on F3=Exit"), "app/bms/MENU00.bms": bms("MENU00", "MENU0A", "ENTER=Go F3=Exit"), "app/cpy/MENU02Y.cpy": MENU_TABLE, "app/cbl/SIGN00C.cbl": SIGNON, "app/cbl/MENU00C.cbl": MENU, "app/csd/DEMO.csd": CSD} -MIXED = {**{f"java/{k}": v for k, v in JAVA_WEB.items() if k.endswith(".java")}, **{f"dotnet/{k}": v for k, v in DOTNET.items() if k.endswith(".cs")}, +MIXED = {**{f"java/{k}": v for k, v in JAVA_WEB.items() if k.endswith(".java") and "Controller" not in k}, **{f"dotnet/{k}": v for k, v in DOTNET.items() if k.endswith(".cs")}, **{f"php/{k}": v for k, v in PHP.items() if k.endswith(".php")}} """Java, C# and PHP, none with more than half the lines.""" From a421340d56630121d71ddc565f909c430fb4051c Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:24:22 -0700 Subject: [PATCH 10/13] L1-06: data contracts from any stack For a codebase that is not a mainframe, the design's data contracts come from what the stack profile found as data (docs/any-legacy.md, section 5.4), in the copybooks' contract shape, so the specifications, the design page and the package use them as they are. - SQL DDL is read with no model: each CREATE TABLE is a record of its columns. Each column carries its SQL type as written, a neutral type (text of n characters, an integer, a decimal with digits and scale, floating point, a date, a timestamp, true or false, binary data), whether it may be empty, and its key: primary, from the column or a PRIMARY KEY clause, or foreign to a table's column. Each cites its line. - Entity and record classes (JPA, Entity Framework and the like) are read by one Claude step per batch of files. Reframe checks that every cited line exists and shows the field's name. A failed answer is asked again once with the reasons, then the file is listed as unread on the design page, never guessed. Unchanged files are not asked again. - The target stack's code and column types apply as for copybooks. A date, a timestamp, a boolean or binary data keeps its neutral type, since Reframe's type tables do not name them; a text with no stated length gets no column size. - A capability's contracts are those its rules' source files name, by table or by entity class. The design page says where they were read from. Tests: the DDL's tables, types, nullability and keys; the stack's types; the Java fixture's table and @Entity, and the second read kept; the .NET entity; a field not on its cited line, asked again and left unread; and the Java design round's contract. Prepared with AI assistance. --- src/reframe/design/designpage.py | 5 +- src/reframe/design/schema.py | 320 +++++++++++++++++++++++++++++++ src/reframe/design/specs.py | 25 ++- tests/design/test_general.py | 8 +- tests/design/test_schema.py | 143 ++++++++++++++ 5 files changed, 493 insertions(+), 8 deletions(-) create mode 100644 src/reframe/design/schema.py create mode 100644 tests/design/test_schema.py diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py index 393b9fbc..381aa9ef 100644 --- a/src/reframe/design/designpage.py +++ b/src/reframe/design/designpage.py @@ -169,6 +169,9 @@ def draw(folder, value: dict[str, Any]) -> Path: if stack else "Target stack: not given yet, so the data contracts show neutral types.") notes = " ".join(e(n) for n in value.get("stack_notes") or [] if stack) contracts = "".join(contract_block(x) for x in value["contracts"].values()) + contracts_how = ("The tables and entities the capabilities' code uses, as typed records: the tables read from the SQL DDL with no model, the " + "entities by a Claude step whose every cited line Reframe checked." if any(x.get("kind") for x in value["contracts"].values()) else + "The copybooks the capabilities' programs copy, as typed records, read from the source with no model.") nav = (f'

    {e(folder.state.get("project") or "")}

    ' if left_out else '

    Legacy screens · Screen flow · Journeys ·\n' f'Modern screens · Prototype · {e(folder.state.get("project") or "")}

    ') @@ -194,7 +197,7 @@ def draw(folder, value: dict[str, Any]) -> Path: {''.join(body_parts)} -

    Data contracts

    The copybooks the capabilities' programs copy, as typed records, read from the source with no model.

    {contracts} +

    Data contracts

    {contracts_how}

    {contracts}

    What the checks still found

      {problems}{more}
    """ target = folder.path(PAGE) diff --git a/src/reframe/design/schema.py b/src/reframe/design/schema.py new file mode 100644 index 00000000..3a4a54e6 --- /dev/null +++ b/src/reframe/design/schema.py @@ -0,0 +1,320 @@ +"""Pipeline 4, stage D6 for any stack: data contracts from the schema and the entities (L1-06, docs/any-legacy.md 5.4). + +For a codebase that is not a mainframe, the contracts come from what the stack profile found as data: + +- **SQL DDL,** read with no model: each `CREATE TABLE` is a record whose fields are its columns, each with its SQL type + as written, a neutral type (text of n characters, an integer, a decimal with its digits and scale, floating point, a + date, a timestamp, true or false, binary data), whether it may be empty, and its key (primary, or foreign to a table's + column), citing the line it is on; +- **entity and record classes** (JPA, Entity Framework, plain classes the ORM maps), read by one Claude step per batch of + files: each entity with its fields, their types as written, the neutral type, the key and whether a value is + required, each citing its line. Reframe checks every cited line exists and shows the field's name; an answer that + fails is asked again once with the reasons, then the file is kept as unread, never guessed. + +The contracts have the copybooks' shape (reframe.design.contracts), so the specifications, the design page and the +package use them as they are. The target stack's code and column types apply as for copybooks; a date, a timestamp, a +boolean or binary data keeps its neutral type, since Reframe's type tables do not name those. + +A program (a source file, L1-02) uses a contract when its code names the table or the entity. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from pathlib import Path, PurePosixPath +from typing import Any + +FILE = "design/schema.json" +METHOD = "schema-1" +BATCH_FILES = 8 +NEUTRAL = ("text", "integer", "decimal", "float", "date", "timestamp", "time", "boolean", "binary") +CODE = {".java", ".kt", ".groovy", ".cs", ".vb", ".py", ".rb", ".php"} + +PROMPT = """Read {input}. It holds entity and record classes of a legacy {languages} application, each with its lines numbered: the classes its code maps to stored data. The legacy source is under {legacy}/ if you need more; do not change anything. + +For each file ("files", one entry per file, "file" exactly as listed), give the entities it defines ("entities"): each with its "name" (the class), the "table" it is stored in if the code says (else empty), its "line", and its "fields": each with "name" (as written), "type" (as written), "neutral" (one of text, integer, decimal, float, date, timestamp, time, boolean, binary), "length" (for text, if the code gives one, else 0), "digits" and "scale" (for a decimal, if the code gives them, else 0), "key" ("primary", "foreign" or empty), "required" (true when the code says a value must be given) and "line" (the line the field is declared on). + +Use only what the files show. A file with no entity gets an empty list. Answer only with the JSON.""" + +RETRY = """Your answer failed Reframe's checks. Answer again with the whole JSON, fixing these: + +{problems}""" + +SCHEMA = {"type": "object", "required": ["files"], "properties": {"files": {"type": "array", "items": { + "type": "object", "required": ["file", "entities"], "properties": {"file": {"type": "string"}, "entities": {"type": "array", "items": { + "type": "object", "required": ["name", "table", "line", "fields"], "properties": { + "name": {"type": "string"}, "table": {"type": "string"}, "line": {"type": "integer"}, + "fields": {"type": "array", "items": {"type": "object", "required": ["name", "type", "neutral", "length", "digits", "scale", "key", "required", "line"], + "properties": {"name": {"type": "string"}, "type": {"type": "string"}, + "neutral": {"type": "string", "enum": list(NEUTRAL)}, "length": {"type": "integer"}, + "digits": {"type": "integer"}, "scale": {"type": "integer"}, + "key": {"type": "string", "enum": ["primary", "foreign", ""]}, + "required": {"type": "boolean"}, "line": {"type": "integer"}}}}}}}}}}}} + + +# ---- neutral types ----------------------------------------------------------------------------------------------------- + +def sql_type(written: str) -> dict[str, Any]: + """An SQL column type -> Reframe's neutral type.""" + t = written.upper().strip() + m = re.match(r"(\w+(?:\s+(?:VARYING|PRECISION))?)\s*(?:\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\))?", t) + name, a, b = (m.group(1), int(m.group(2) or 0), int(m.group(3) or 0)) if m else (t, 0, 0) + if name in ("CHAR", "CHARACTER", "VARCHAR", "VARCHAR2", "NVARCHAR", "NCHAR", "CHARACTER VARYING", "TEXT", "CLOB", "STRING"): + return {"type": "text", "length": a, "storage": "characters", "bytes": a} + if name in ("SMALLINT", "INT", "INTEGER", "BIGINT", "TINYINT", "MEDIUMINT", "SERIAL", "BIGSERIAL"): + digits = {"TINYINT": 3, "SMALLINT": 5, "MEDIUMINT": 7, "BIGINT": 19, "BIGSERIAL": 19}.get(name, 10) + return {"type": "integer", "digits": digits, "scale": 0, "signed": True, "storage": "binary", "bytes": 8 if digits > 10 else 4} + if name in ("DECIMAL", "NUMERIC", "DEC", "NUMBER", "MONEY"): + return {"type": "decimal" if b else "integer", "digits": a or 18, "scale": b, "signed": True, "storage": "decimal", "bytes": 0} + if name in ("FLOAT", "REAL", "DOUBLE", "DOUBLE PRECISION"): + return {"type": "float", "storage": "double float" if name != "REAL" else "single float", "bytes": 8} + if name in ("DATE",): + return {"type": "date"} + if name in ("TIMESTAMP", "DATETIME", "DATETIME2", "TIMESTAMPTZ"): + return {"type": "timestamp"} + if name in ("TIME",): + return {"type": "time"} + if name in ("BOOLEAN", "BOOL", "BIT"): + return {"type": "boolean"} + if name in ("BLOB", "BINARY", "VARBINARY", "BYTEA", "IMAGE"): + return {"type": "binary"} + return {"type": "unknown"} + + +def from_answer(f: dict[str, Any]) -> dict[str, Any]: + kind = f.get("neutral") or "unknown" + if kind == "text": + return {"type": "text", "length": int(f.get("length") or 0), "storage": "characters", "bytes": int(f.get("length") or 0)} + if kind in ("integer", "decimal"): + return {"type": kind, "digits": int(f.get("digits") or (18 if kind == "decimal" else 10)), "scale": int(f.get("scale") or 0), + "signed": True, "storage": "decimal" if kind == "decimal" else "binary", "bytes": 0} + if kind == "float": + return {"type": "float", "storage": "double float", "bytes": 8} + return {"type": kind} + + +def says(t: dict[str, Any]) -> str: + from reframe.design.contracts import describe + kind = t.get("type") + if kind == "text": + return f"text, {t['length']} characters" if t.get("length") else "text" + if kind in ("integer", "decimal") and t.get("storage") in ("binary", "decimal"): + return (f"integer, {t['digits']} digits" if kind == "integer" else f"decimal, {t['digits'] - t['scale']} integer and {t['scale']} fraction digits") + return {"date": "date", "timestamp": "date and time", "time": "time of day", "boolean": "true or false", "binary": "binary data", + "unknown": "a type Reframe does not know"}.get(str(kind)) or describe(t) + + +def typed(t: dict[str, Any], types: dict[str, Any]) -> dict[str, str]: + from reframe.design.contracts import on_stack + if t.get("type") == "text" and not t.get("length"): + return {} # a text of no stated length: Reframe gives no column size it was not told + return on_stack(t, types) + + +# ---- SQL DDL, with no model -------------------------------------------------------------------------------------------- + +CREATE = re.compile(r"\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"`\[\]]+)\s*\(", re.I) + + +def _split(body: str) -> list[tuple[str, int]]: + """The comma-separated parts of a table body at depth 0, each with its offset.""" + parts, depth, start = [], 0, 0 + for i, ch in enumerate(body): + if ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + elif ch == "," and depth == 0: + parts.append((body[start:i], start)) + start = i + 1 + parts.append((body[start:], start)) + return parts + + +def tables(text: str, rel: str, types: dict[str, Any]) -> list[dict[str, Any]]: + """Every CREATE TABLE in one file, as contracts.""" + found = [] + for m in CREATE.finditer(text): + depth, end = 1, m.end() + while end < len(text) and depth: + depth += {"(": 1, ")": -1}.get(text[end], 0) + end += 1 + body, base = text[m.end():end - 1], m.end() + name = m.group(1).strip('"`[]').split(".")[-1] + fields, primary, foreign = [], set(), {} + for part, offset in _split(body): + clause = " ".join(part.split()) + if not clause: + continue + line = text[:base + offset + len(part) - len(part.lstrip())].count("\n") + 1 + pk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?PRIMARY\s+KEY\s*\(([^)]*)\)", clause, re.I) + fk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s*REFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", clause, re.I) + if pk: + primary |= {c.strip().strip('"`').upper() for c in pk.group(1).split(",")} + continue + if fk: + foreign[fk.group(1).strip().strip('"`').upper()] = f"{fk.group(2).strip(chr(34) + '`')}({fk.group(3).strip()})" + continue + if re.match(r"(CONSTRAINT|UNIQUE|CHECK|INDEX|KEY)\b", clause, re.I): + continue + col = re.match(r"([\w\"`\[\]]+)\s+(.+)", clause) + if not col: + continue + cname, rest = col.group(1).strip('"`[]'), col.group(2) + written = re.match(r"[\w ]+?(?:\([^)]*\))?(?=\s+(?:NOT|NULL|DEFAULT|PRIMARY|REFERENCES|UNIQUE|CHECK|CONSTRAINT|GENERATED|AUTO_INCREMENT|IDENTITY)\b|\s*$)", + rest, re.I) + sql = (written.group(0) if written else rest.split()[0]).strip() + t = sql_type(sql) + ref = re.search(r"\bREFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", rest, re.I) + if re.search(r"\bPRIMARY\s+KEY\b", rest, re.I): + primary.add(cname.upper()) + if ref: + foreign[cname.upper()] = f"{ref.group(1).strip(chr(34) + '`')}({ref.group(2).strip()})" + field = {"name": cname, "level": 1, "group": "", "pic": sql, "usage": " ".join(rest[len(sql):].split()), **t, "says": says(t), + "line": line, "nullable": not re.search(r"\bNOT\s+NULL\b|\bPRIMARY\s+KEY\b", rest, re.I)} + stack = typed(t, types) + if stack: + field["stack"] = stack + fields.append(field) + for f in fields: + if f["name"].upper() in primary: + f["key"] = "primary" + elif f["name"].upper() in foreign: + f["key"] = f"foreign: {foreign[f['name'].upper()]}" + found.append({"copybook": name.upper(), "kind": "table", "file": rel, "how": "SQL DDL, read with no model", + "records": [{"name": name, "line": text[:m.start()].count("\n") + 1, "fields": fields}]}) + return found + + +# ---- entities, by a checked Claude step -------------------------------------------------------------------------------- + +def _lines(legacy: Path, rel: str) -> list[str]: + try: + return (legacy / rel).read_text(errors="replace").splitlines() + except OSError: + return [] + + +def problems(answer: dict[str, Any] | None, batch: list[str], legacy: Path) -> list[str]: + if not answer or not isinstance(answer.get("files"), list): + return ["no answer"] + found, seen = [], set() + for f in answer["files"]: + name = f.get("file") + if name not in batch: + found.append(f"{name}: not a file of this batch") + continue + seen.add(name) + lines = _lines(legacy, name) + for e in f.get("entities") or []: + if not 1 <= int(e.get("line") or 0) <= len(lines): + found.append(f"{name}: entity {e.get('name')!r} cites line {e.get('line')}, which {name} does not have") + for x in e.get("fields") or []: + n = int(x.get("line") or 0) + if not 1 <= n <= len(lines): + found.append(f"{name}: field {x.get('name')!r} cites line {n}, which {name} does not have ({len(lines)} lines)") + elif str(x.get("name") or "") not in lines[n - 1]: + found.append(f"{name}: field {x.get('name')!r} is not on line {n}") + found += [f"{name}: missing from the answer" for name in batch if name not in seen] + return found + + +def entities(folder, claude, legacy: Path, files: list[str], words: str, types: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]: + """The entity classes of the files, as contracts, and the problems left after the second answer.""" + from reframe.claude.steps import stop_for + from reframe.claude.workspace import paths + saved = folder.load(FILE, {}) or {} + kept, log = saved.get("entities") or {}, saved.get("log") or [] + places, project = paths(folder), folder.state["project"] + folder_in = places["analysis"] / "reframe" / "design" + left: list[str] = [] + out: list[dict[str, Any]] = [] + for i in range(0, len(files), BATCH_FILES): + batch = files[i:i + BATCH_FILES] + data = {"files": [{"file": f, "lines": "\n".join(f"{n:5} {x}" for n, x in enumerate(_lines(legacy, f), 1))} for f in batch]} + key = f"b{i // BATCH_FILES + 1}" + digest = hashlib.sha256(json.dumps([data, METHOD], sort_keys=True).encode()).hexdigest()[:16] + before = kept.get(key) or {} + if before.get("hash") != digest or before.get("problems"): + if claude is None: + left.append(f"{', '.join(batch)}: not read yet") + continue + folder_in.mkdir(parents=True, exist_ok=True) + path = folder_in / f"schema-entities-{key}.json" + path.write_text(json.dumps(data, indent=1)) + prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", languages=words) + answer, wrong = None, ["no answer"] + for attempt in (1, 2): + step = claude.run(f"schema-entities-{key}{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else + prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=SCHEMA) + log.append({"part": key, "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}}) + if not step.ok: + if step.problem in ("limit", "signin"): + folder.save(FILE, {**saved, "entities": kept, "log": log}) + raise stop_for(step, "the data contracts") + wrong = [f"the step did not finish ({step.problem})"] + continue + answer = claude.structured(step) + wrong = problems(answer, batch, legacy) + if not wrong: + break + before = kept[key] = {"hash": digest, "answer": None if wrong else answer, "problems": wrong} + folder.save(FILE, {**saved, "entities": kept, "log": log}) + left += before.get("problems") or [] + for f in (before.get("answer") or {}).get("files") or []: + for e in f.get("entities") or []: + fields = [] + for x in e.get("fields") or []: + t = from_answer(x) + field = {"name": x["name"], "level": 1, "group": "", "pic": x.get("type", ""), "usage": "required" if x.get("required") else "", + **t, "says": says(t), "line": int(x["line"]), "nullable": not x.get("required")} + if x.get("key"): + field["key"] = x["key"] + stack = typed(t, types) + if stack: + field["stack"] = stack + fields.append(field) + out.append({"copybook": str(e["name"]).upper(), "kind": "entity", "file": f["file"], "table": e.get("table") or "", + "how": "entity class, read by a Claude step Reframe checked", "records": [{"name": e["name"], "line": int(e["line"]), "fields": fields}]}) + return out, left + + +# ---- all of it --------------------------------------------------------------------------------------------------------- + +def read(folder, claude, legacy: Path, stack: dict[str, Any], types: dict[str, Any]) -> dict[str, Any]: + """Every contract of a codebase that is not a mainframe: its tables, with no model, and its entities, by a checked step.""" + from reframe.source import profile + data_files = profile.files_with(legacy, "data") + found: dict[str, dict[str, Any]] = {} + for rel in data_files: + if PurePosixPath(rel).suffix.lower() in (".sql", ".ddl"): + for c in tables((legacy / rel).read_text(errors="replace"), rel, types): + found.setdefault(c["copybook"], c) + code = [rel for rel in data_files if PurePosixPath(rel).suffix.lower() in CODE] + made, left = entities(folder, claude, legacy, code, stack["words"]["languages"], types) + for c in made: + name = c["copybook"] if c["copybook"] not in found else f"{c['copybook']}-ENTITY" + found[name] = {**c, "copybook": name} + return {"contracts": found, "problems": left} + + +def uses(legacy: Path, contracts: dict[str, dict[str, Any]]) -> dict[str, dict[str, str]]: + """For each source file (the program, L1-02), the contracts its code names: a table by its name, an entity by its class.""" + from reframe.source import kinds, profile + words = {name: {c["records"][0]["name"], *([c["table"]] if c.get("table") else [])} for name, c in contracts.items()} + found: dict[str, dict[str, str]] = {} + for p in sorted(legacy.rglob("*")): + if not p.is_file(): + continue + rel = p.relative_to(legacy).as_posix() + if profile.is_library(rel) or profile.language(rel, kinds.read_head(p)) in (None, "SQL"): + continue + text = p.read_text(errors="replace") + mine = {name: ("table" if c["kind"] == "table" else "entity") for name, c in contracts.items() + if c["file"] != rel and any(re.search(rf"\b{re.escape(w)}\b", text, re.I if c["kind"] == "table" else 0) for w in words[name])} + mine.update({name: "entity" for name, c in contracts.items() if c["file"] == rel}) + if mine: + found[rel.upper()] = mine + return found diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index 958a7368..20ee13b4 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -191,7 +191,8 @@ def questions_for(rule_keys: list[str], rules: dict[str, Any], sme: list[dict[st return found -def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]: +def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None, + contracts: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]: """Every capability's specification without the model's parts, and what the model step is to write for each.""" requirements = folder.load("outputs/reconcile/requirements.json") or {} rules = {r["key"]: r for r in (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or []} @@ -205,7 +206,11 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None signed[x["function"]].append({"reviewer": x.get("reviewer", ""), "at": x.get("at", ""), "comment": x.get("comment", "")}) online = {p["name"].upper() for s in inventory.get("screens") or [] for p in s.get("programs") or []} | \ {str(t.get("program", "")).upper() for t in flow.get("transactions") or []} - uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {} + if contracts is not None: # any stack but the mainframe (L1-06): the tables and entities each source file names + from reframe.design import schema + uses = schema.uses(legacy, contracts) if legacy and legacy.is_dir() else {} + else: + uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {} domain_of = {f: d for d in requirements.get("domains") or [] for f in d.get("functions") or []} names = requirements.get("names") or {} found = [] @@ -412,8 +417,18 @@ def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = F raise ValueError("run the screen inventory, the flow, the journeys and the modern screens first") target = stack_of(folder, None if plan_only else stack) types = data_contracts.stack_types(target) - built = assemble(folder, places["legacy"], signoffs) - books = data_contracts.contracts(places["legacy"], set(built["books"]), types) + from reframe.source import profile + stack_profile = profile.of_run(folder) + schema_problems: list[str] = [] + if stack_profile.get("family", "mainframe") == "mainframe": + built = assemble(folder, places["legacy"], signoffs) + books = data_contracts.contracts(places["legacy"], set(built["books"]), types) + else: # the schema with no model and the entities by a checked step (L1-06) + from reframe.design import schema + read = schema.read(folder, None if plan_only else claude, places["legacy"], stack_profile, types) + schema_problems = [f"data contracts: {p}" for p in read["problems"]] + built = assemble(folder, places["legacy"], signoffs, read["contracts"]) + books = {name: c for name, c in read["contracts"].items() if name in set(built["books"])} if not plan_only: folder.save(CONTRACTS, {"stack": target, "notes": types["notes"], "contracts": books}) saved = folder.load(FILE, {}) or {} @@ -493,7 +508,7 @@ def one(item) -> None: value = {"batches": kept, "log": log, "stack": target, "stack_notes": types["notes"], "specs": [{k: s[k] for k in ("key", "function", "function_name", "domain", "number", "title", "status", "runs_as")} for s in specs], "counts": counts(specs, books), - "problems": batch_problems + found, + "problems": batch_problems + schema_problems + found, "steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)} folder.save(FILE, value) value["full"] = specs diff --git a/tests/design/test_general.py b/tests/design/test_general.py index 6fb9d3ba..740ac1dd 100644 --- a/tests/design/test_general.py +++ b/tests/design/test_general.py @@ -91,7 +91,8 @@ def run_for(self, name, reader=read_views): self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", stacks.FIXTURES[name]) self.stack = profile.profile_folder(self.legacy) self.folder.save(profile.FILE, self.stack) - self.claude = FakeClaude(reader=reader, journeys=journeys_for, screens=screens_for, specs=written) + from tests.design.test_schema import read_entities + self.claude = FakeClaude(reader=reader, journeys=journeys_for, screens=screens_for, specs=written, schema=read_entities) self.claude.root = self.folder.root / "claude" views = profile.files_with(self.legacy, "ui") found = general.read_screens(self.folder, self.claude, self.legacy, views, self.stack["words"]["languages"]) @@ -221,7 +222,10 @@ def test_a_design_round_on_java(self): self.assertIn("general reader", self.folder.path("outputs/design/legacy/index.html").read_text()) self.assertIn("Customer", self.folder.path("outputs/design/legacy/ORDERS-NEW.html").read_text()) self.assertIn("Read by Reframe's general reader", self.folder.path("outputs/design/flow.html").read_text()) - self.assertIn("general reader", self.folder.path("outputs/design/index.html").read_text()) + page = self.folder.path("outputs/design/index.html").read_text() + self.assertIn("general reader", page) + self.assertIn("the tables read from the SQL DDL with no model", page) # L1-06: the service behind the rule names the Order entity + self.assertIn('id="contract-ORDER"', page) if __name__ == "__main__": diff --git a/tests/design/test_schema.py b/tests/design/test_schema.py new file mode 100644 index 00000000..57b576ac --- /dev/null +++ b/tests/design/test_schema.py @@ -0,0 +1,143 @@ +"""L1-06: data contracts from any stack (docs/any-legacy.md, section 5.4). SQL DDL is read with no model; entity classes +by a checked model step; the target stack's types apply as today.""" +import os +import re +import tempfile +import unittest +from unittest import mock + +from reframe.core.runfolder import new_run +from reframe.design import contracts, schema +from reframe.source import profile +from tests import stacks +from tests.reconcile.test_decide import FakeClaude + +DDL = """-- the shop's schema +CREATE TABLE CUSTOMER ( + ID BIGINT NOT NULL, + NAME VARCHAR(40) NOT NULL, + CREDIT DECIMAL(9,2) DEFAULT 0, + JOINED DATE, + ACTIVE BOOLEAN, + PRIMARY KEY (ID) +); +CREATE TABLE IF NOT EXISTS ORDERS ( + ID BIGINT PRIMARY KEY, + CUSTOMER_ID BIGINT NOT NULL REFERENCES CUSTOMER(ID), + TOTAL NUMERIC(10, 2), + NOTE TEXT, + CONSTRAINT FK_X FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER (ID) +); +""" +JAVA_FIELD = re.compile(r"private\s+(\w+)\s+(\w+)\s*;") +CS_FIELD = re.compile(r"public\s+(\w+)\s+(\w+)\s*\{\s*get;") +NEUTRAL = {"String": "text", "string": "text", "int": "integer", "Long": "integer", "BigDecimal": "decimal", "decimal": "decimal"} + + +def read_entities(data): + """What the step answers: each class's fields as declared, with the lines they are on.""" + files = [] + for f in data["files"]: + rows = [r.strip().partition(" ") for r in f["lines"].splitlines()] + found, fields, line_of = None, [], 0 + for n, _, line in rows: + m = re.search(r"class\s+(\w+)", line) + if m and found is None: + found, line_of = m.group(1), int(n) + for pattern in (JAVA_FIELD, CS_FIELD): + for t, name in pattern.findall(line): + fields.append({"name": name, "type": t, "neutral": NEUTRAL.get(t, "text"), "length": 40 if name in ("customer", "Customer") else 0, + "digits": 0, "scale": 0, "key": "primary" if name in ("id", "Id") else "", "required": name in ("customer", "Customer"), + "line": int(n)}) + entities = [{"name": found, "table": "ORDERS" if "ORDERS" in f["lines"] else "Orders" if "Orders" in f["lines"] else "", "line": line_of, + "fields": fields}] if found and fields else [] + files.append({"file": f["file"], "entities": entities}) + return {"files": files} + + +def misplaced(data): + answer = read_entities(data) + for f in answer["files"]: + for e in f["entities"]: + for x in e["fields"]: + x["line"] = e["line"] # the class's line, not the field's + return answer + + +class DdlTest(unittest.TestCase): + def test_tables_columns_types_keys_with_no_model(self): + found = {c["copybook"]: c for c in schema.tables(DDL, "db/schema.sql", contracts.stack_types(None))} + self.assertEqual(sorted(found), ["CUSTOMER", "ORDERS"]) + customer = {f["name"]: f for f in found["CUSTOMER"]["records"][0]["fields"]} + self.assertEqual([f for f in customer], ["ID", "NAME", "CREDIT", "JOINED", "ACTIVE"]) # the PRIMARY KEY clause is a key, not a column + self.assertEqual((customer["NAME"]["type"], customer["NAME"]["length"], customer["NAME"]["nullable"], customer["NAME"]["line"]), ("text", 40, False, 4)) + self.assertEqual((customer["CREDIT"]["type"], customer["CREDIT"]["digits"], customer["CREDIT"]["scale"]), ("decimal", 9, 2)) + self.assertEqual(customer["CREDIT"]["says"], "decimal, 7 integer and 2 fraction digits") + self.assertEqual((customer["JOINED"]["says"], customer["ACTIVE"]["says"]), ("date", "true or false")) + self.assertEqual(customer["ID"]["key"], "primary") + orders = {f["name"]: f for f in found["ORDERS"]["records"][0]["fields"]} + self.assertEqual(orders["ID"]["key"], "primary") + self.assertEqual(orders["CUSTOMER_ID"]["key"], "foreign: CUSTOMER(ID)") + self.assertEqual(orders["NOTE"]["says"], "text") + self.assertEqual(found["ORDERS"]["how"], "SQL DDL, read with no model") + + def test_the_target_stacks_types_apply_as_today(self): + types = contracts.stack_types(contracts.parse_stack("React; Java 21 with Spring Boot; PostgreSQL")) + found = {c["copybook"]: c for c in schema.tables(DDL, "db/schema.sql", types)} + customer = {f["name"]: f for f in found["CUSTOMER"]["records"][0]["fields"]} + self.assertEqual(customer["NAME"]["stack"], {"code": "String", "column": "VARCHAR(40)"}) + self.assertEqual(customer["CREDIT"]["stack"], {"code": "BigDecimal", "column": "NUMERIC(9,2)"}) + self.assertNotIn("stack", customer["JOINED"]) # no type table names a date: the neutral type stands + + +class EntitiesTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name}) + env.start() + self.addCleanup(env.stop) + + def read(self, name, answer=read_entities): + self.folder = new_run(name.replace("-", "")) + self.folder.update(project="shop", tools="claude") + self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", stacks.FIXTURES[name]) + self.claude = FakeClaude(schema=answer) + self.claude.root = self.folder.root / "claude" + return schema.read(self.folder, self.claude, self.legacy, profile.profile_folder(self.legacy), contracts.stack_types(None)) + + def test_java_the_schema_and_the_entity(self): + found = self.read("java") + self.assertEqual(sorted(found["contracts"]), ["ORDER", "ORDERS"]) # the table, with no model, and the @Entity class, by the step + self.assertEqual(found["problems"], []) + entity = found["contracts"]["ORDER"] + self.assertEqual((entity["kind"], entity["table"], entity["file"]), ("entity", "ORDERS", "src/main/java/org/demo/shop/model/Order.java")) + fields = {f["name"]: f for f in entity["records"][0]["fields"]} + self.assertEqual((fields["customer"]["says"], fields["customer"]["line"], fields["id"]["key"]), ("text, 40 characters", 12, "primary")) + self.assertEqual(fields["total"]["type"], "decimal") + self.assertEqual([c[0] for c in self.claude.other_calls], ["schema-entities-b1"]) + uses = schema.uses(self.legacy, found["contracts"]) + self.assertEqual(uses["SRC/MAIN/JAVA/ORG/DEMO/SHOP/SERVICE/ORDERSERVICE.JAVA"], {"ORDER": "entity"}) # the service names the class + self.read_again_is_kept() + + def read_again_is_kept(self): + before = len(self.claude.other_calls) + schema.read(self.folder, self.claude, self.legacy, profile.profile_folder(self.legacy), contracts.stack_types(None)) + self.assertEqual(len(self.claude.other_calls), before) # nothing changed: no step + + def test_dotnet_entities_beside_the_db_context(self): + found = self.read("dotnet") + self.assertIn("ORDER", found["contracts"]) + fields = [f["name"] for f in found["contracts"]["ORDER"]["records"][0]["fields"]] + self.assertEqual(fields, ["Id", "Customer", "Quantity", "Total"]) + + def test_a_field_not_on_its_cited_line_is_asked_again_then_left_unread(self): + found = self.read("java", answer=misplaced) + self.assertEqual([c[0] for c in self.claude.other_calls], ["schema-entities-b1", "schema-entities-b1-retry"]) + self.assertIn("is not on line", self.claude.other_calls[1][2]) + self.assertEqual(sorted(found["contracts"]), ["ORDERS"]) # the table still stands; the entity is not guessed + self.assertTrue(any("is not on line" in p for p in found["problems"])) + + +if __name__ == "__main__": + unittest.main() From 97bc567fe056778c339de85ac26ad140fbb8a1b7 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:26:59 -0700 Subject: [PATCH 11/13] L1-07: "runs as" for any stack Each capability's "runs as" comes from the screens, routes and job definitions of any stack (docs/any-legacy.md, section 5.4). The mainframe's rule is unchanged. - Online: the capability's rules are in code behind a screen. That is the view, the handlers that render it, the handler its form posts to, and the classes they use. - Scheduled job: the code is a job definition (cron, Quartz, Spring Batch, @Scheduled, Windows tasks, JCL), or a file one uses, or a rule's entry cites one. Both online and a scheduled job give "online and scheduled job", as before. - Service: routes reach the code and no screen does. - Library: nothing in the source shows how the code runs. The package's API task then builds the library the rest of the application calls, and the specification counts list it. Tests: for each fixture (the Java web application online and its nightly job, .NET online, the PHP form handler online, the batch-only job), a REST service with no screens and a helper nothing runs, the mainframe's rule as before, and the batch fixture's design round. Prepared with AI assistance. --- src/reframe/design/general.py | 3 +- src/reframe/design/package.py | 2 +- src/reframe/design/specs.py | 40 ++++++++++-- tests/design/test_no_screens.py | 1 + tests/design/test_runs_as.py | 110 ++++++++++++++++++++++++++++++++ tests/stacks.py | 4 ++ 6 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 tests/design/test_runs_as.py diff --git a/src/reframe/design/general.py b/src/reframe/design/general.py index d3f148e1..5709a1d3 100644 --- a/src/reframe/design/general.py +++ b/src/reframe/design/general.py @@ -355,7 +355,8 @@ def target_of(raw: str, where: str) -> str | None: resolved, unresolved = settle(folder, claude, legacy, unsettled, views, table, stack, plan_only) links += resolved for s in screens["screens"]: # the code behind a screen: the handlers that render it and what they use - handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table}) + handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table} + | {table[x["to"]]["handler"] for x in links if x["kind"] == "form" and x["from"] == s["file"] and x["to"] in table}) used = sorted({f for h in handlers for f in used_files(legacy, h, stems)}) s["programs"] = [{"name": p, "file": p} for p in dict.fromkeys([s["file"], *handlers, *used])] reached = {sid for link in links if link["kind"] != "renders" for sid in screens_of.get(link["to"], set())} diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py index 78823390..fb3a0ff0 100644 --- a/src/reframe/design/package.py +++ b/src/reframe/design/package.py @@ -175,7 +175,7 @@ def add(role: str, title: str, qs: list[dict[str, Any]], details: list[str], dep add("business-rules", "Implement error handling and messages", by_class["error handling"] + by_class["formatting"], ["Show every message word for word; formatting rules may be restyled to the design system."], first) shape = {"online": "the services behind the screens", "scheduled job": "the scheduled job", "online and scheduled job": "the services and the scheduled job", - "service": "the service"}[s["runs_as"]] + "service": "the service", "library": "the library the rest of the application calls"}[s["runs_as"]] notes = [f"{rid.get(n['rule'], n['rule'])}: {n['note']}" for n in s["design_notes"]] add("api", f"Build {shape}", by_class["design note"] or (reqs if s["runs_as"] != "online" and not s["screens"] else []), notes or ["Expose the rules as the service the screens call."], [t["id"] for t in found if t["role"] in ("data", "business-rules")]) diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index 20ee13b4..5773140e 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -139,13 +139,39 @@ def example_criteria(reqs: list[dict[str, Any]], rules: dict[str, Any]) -> list[ return found -def runs_as(rules: list[dict[str, Any]], online: set[str]) -> str: +def what_runs(legacy: Path) -> tuple[set[str], set[str]]: + """For any stack but the mainframe (L1-07): the source files of job definitions and of routes, each with the files it + uses, by path in capitals (a program's name, L1-02).""" + from reframe.design.general import used_files + from reframe.source import profile + stems: dict[str, list[str]] = defaultdict(list) + for item in legacy.rglob("*"): + if item.is_file(): + stems[item.stem].append(item.relative_to(legacy).as_posix()) + jobs: set[str] = set() + routes: set[str] = set() + for what, into in (("jobs", jobs), ("routes", routes)): + for rel in profile.files_with(legacy, what): + into |= {x.upper() for x in [rel, *used_files(legacy, rel, stems)]} + return jobs, routes + + +def runs_as(rules: list[dict[str, Any]], online: set[str], jobs: set[str] | None = None, routes: set[str] | None = None) -> str: """How the capability runs in the new application: online (behind screens), as a scheduled job (from JCL), or both; - a service when the source shows neither.""" + a service when the source shows neither. For any stack but the mainframe (L1-07, docs/any-legacy.md section 5.4), + `jobs` and `routes` are the source files of job definitions and routes, with the files they use: a rule whose code + is one of them, or whose entry cites one, runs as a scheduled job, or as a service when no screen reaches it; a + library when nothing in the source shows how it runs.""" entries = [e.lower() for r in rules for e in r.get("entry") or []] on = any("/csd/" in e or e.endswith(".csd") for e in entries) or any(str(r.get("program", "")).upper() in online for r in rules) job = any(re.search(r"/(jcl|proc|scheduler)/|\.jcl\b|\.prc\b", e) for e in entries) - return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service" + if jobs is None: + return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service" + code = {str(r.get("program", "")).upper() for r in rules} | {e.rsplit(":", 1)[0].upper() for e in entries} + on = on or bool(code & online) + job = job or bool(code & jobs) + served = bool(code & (routes or set())) + return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service" if served else "library" def screens_for(key: str, codes: set[str], rule_keys: set[str], modern: dict[str, Any], journeys: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]: @@ -206,9 +232,13 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None signed[x["function"]].append({"reviewer": x.get("reviewer", ""), "at": x.get("at", ""), "comment": x.get("comment", "")}) online = {p["name"].upper() for s in inventory.get("screens") or [] for p in s.get("programs") or []} | \ {str(t.get("program", "")).upper() for t in flow.get("transactions") or []} + jobs: set[str] | None = None + routes: set[str] | None = None if contracts is not None: # any stack but the mainframe (L1-06): the tables and entities each source file names from reframe.design import schema uses = schema.uses(legacy, contracts) if legacy and legacy.is_dir() else {} + if legacy and legacy.is_dir(): + jobs, routes = what_runs(legacy) else: uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {} domain_of = {f: d for d in requirements.get("domains") or [] for f in d.get("functions") or []} @@ -239,7 +269,7 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None "domain_key": domain.get("key", ""), "number": cap["number"], "title": cap.get("title", ""), "story": cap.get("story", ""), "risk": cap.get("risk", ""), "touches": cap.get("touches") or [], "status": "final" if signed.get(page) else "draft", "signed_off": signed.get(page) or [], - "runs_as": runs_as(mine, online), + "runs_as": runs_as(mine, online, jobs, routes), "requirements": [{"key": f"{page}/{q['code']}", "code": q["code"], "kind": q.get("kind", ""), "pattern": q.get("pattern", ""), "text": q["text"], "rules": q.get("rules") or [], "class": requirement_class([rules[k] for k in q.get("rules") or [] if k in rules])} for q in reqs], "rules": [{"key": r["key"], "name": r.get("name", ""), "kind": r.get("kind", ""), "class": class_of(r.get("kind", "")), @@ -526,7 +556,7 @@ def counts(specs: list[dict[str, Any]], books: dict[str, Any]) -> dict[str, Any] "contracts": len(books), "tables": sum(len(s["tables"]) for s in specs), "gaps": sum(s["gaps"] for s in specs), "questions": len({q["id"] or q["question"] for s in specs for q in s["questions"]}), "classes": {c: sum(1 for s in specs for r in s["rules"] if r["class"] == c) for c in CLASS_ORDER}, - "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service")}} + "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service", "library")}} def main(argv: list[str] | None = None) -> int: diff --git a/tests/design/test_no_screens.py b/tests/design/test_no_screens.py index 17e4a245..6219b813 100644 --- a/tests/design/test_no_screens.py +++ b/tests/design/test_no_screens.py @@ -68,6 +68,7 @@ def test_specifications_golden_datasets_package_and_backlog_without_screens(self self.assertIn("no screens", value["stages"][stage]["left_out"]) self.assertEqual([c[0].split("-")[0] for c in self.claude.other_calls], ["specs"]) # only the specifications' step self.assertEqual(value["stages"]["specs"]["redone"][0]["name"], "Billing/Invoice") + self.assertEqual([s["runs_as"] for s in self.folder.load("design/specs.json")["specs"]], ["scheduled job"]) # L1-07: the batch job uses it self.assertFalse(self.folder.path("outputs/design/prototype/index.html").exists()) self.assertIn("- Left out: the codebase has no screens.", self.folder.path("design/changes-1.md").read_text()) page = self.folder.path("outputs/design/index.html").read_text() diff --git a/tests/design/test_runs_as.py b/tests/design/test_runs_as.py new file mode 100644 index 00000000..2af133ad --- /dev/null +++ b/tests/design/test_runs_as.py @@ -0,0 +1,110 @@ +"""L1-07: "runs as" for any stack (docs/any-legacy.md, section 5.4): online, scheduled job, service or library from the +screens, routes and job definitions, for each fixture. The mainframe's rule is unchanged.""" +import os +import tempfile +import unittest +from unittest import mock + +from reframe.core.runfolder import new_run +from reframe.design import general, specs +from reframe.source import profile +from tests import stacks +from tests.design.test_general import read_views +from tests.reconcile.test_decide import FakeClaude + +SERVICE = { # a REST service with no screens, and a helper nothing runs + "src/main/java/org/demo/rates/RateResource.java": """package org.demo.rates; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/rates") +public class RateResource { + private final RateTable table = new RateTable(); + + @GET + public String rate() { + return table.current(); + } +} +""", + "src/main/java/org/demo/rates/RateTable.java": """package org.demo.rates; + +public class RateTable { + public String current() { + return "4.25"; + } +} +""", + "src/main/java/org/demo/rates/Rounding.java": """package org.demo.rates; + +public class Rounding { + public static double half(double x) { + return Math.round(x * 100) / 100.0; + } +} +""", +} + + +def rule(program, entry=()): + return {"key": f"rec/{program}", "program": program.upper(), "entry": list(entry)} + + +class RunsAsTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name}) + env.start() + self.addCleanup(env.stop) + + def context(self, files, name="fixture"): + """The online programs (behind the general reader's screens), and the jobs and routes, as assemble works them out.""" + folder = new_run(name) + folder.update(project="x", tools="claude") + legacy = stacks.write(folder.root / "claude" / "legacy" / "x", files) + stack = profile.profile_folder(legacy) + folder.save(profile.FILE, stack) + claude = FakeClaude(reader=read_views) + claude.root = folder.root / "claude" + found = general.read_screens(folder, claude, legacy, profile.files_with(legacy, "ui"), "x") + general.read_flow(folder, claude, legacy, found, stack) + folder.save("design/screens.json", found) + online = {p["name"].upper() for s in found["screens"] for p in s["programs"]} # as assemble reads it from design/screens.json + jobs, routes = specs.what_runs(legacy) + return lambda *rules: specs.runs_as(list(rules), online, jobs, routes) + + def test_java_web_online_and_a_scheduled_job(self): + runs = self.context(stacks.JAVA_WEB) + self.assertEqual(runs(rule("src/main/java/org/demo/shop/service/OrderService.java")), "online") # behind the order screens + self.assertEqual(runs(rule("src/main/java/org/demo/shop/jobs/NightlyReport.java")), "scheduled job") # @Scheduled + self.assertEqual(runs(rule("src/main/java/org/demo/shop/service/OrderService.java"), rule("src/main/java/org/demo/shop/jobs/NightlyReport.java")), + "online and scheduled job") + + def test_dotnet_online(self): + runs = self.context(stacks.DOTNET) + self.assertEqual(runs(rule("Shop/Controllers/OrdersController.cs")), "online") + + def test_php_the_form_handler_is_online(self): + runs = self.context(stacks.PHP) + self.assertEqual(runs(rule("orders.php")), "online") # the page's form posts to it + + def test_batch_a_scheduled_job(self): + runs = self.context(stacks.BATCH) + self.assertEqual(runs(rule("src/main/java/org/demo/billing/InvoiceProcessor.java")), "scheduled job") # the batch job uses it + self.assertEqual(runs(rule("src/main/java/org/demo/billing/X.java", ["deploy/crontab:1"])), "scheduled job") # an entry in the crontab + + def test_a_service_with_no_screens_and_a_library(self): + runs = self.context(SERVICE) + self.assertEqual(runs(rule("src/main/java/org/demo/rates/RateTable.java")), "service") # a route reaches it, no screen does + self.assertEqual(runs(rule("src/main/java/org/demo/rates/Rounding.java")), "library") # nothing in the source runs it + + def test_the_mainframe_rule_is_unchanged(self): + self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": ["app/jcl/RUN.jcl:3"]}], set()), "scheduled job") + self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": []}], set()), "service") # no "library" on the mainframe + self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": []}], {"PROG1"}), "online") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/stacks.py b/tests/stacks.py index e6ba356f..b4b2fd3b 100644 --- a/tests/stacks.py +++ b/tests/stacks.py @@ -276,6 +276,10 @@ @EnableBatchProcessing public class BillingJobConfig { public static final String JOB = "monthlyBilling"; + + public InvoiceProcessor processor() { + return new InvoiceProcessor(); + } } """, "src/main/java/org/demo/billing/InvoiceProcessor.java": """package org.demo.billing; From 7c3ce1318a24d9d431a27b0e6b2b5be579379c04 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:29:49 -0700 Subject: [PATCH 12/13] L1-08: words, README and docs Reframe's words follow docs/any-legacy.md, section 6: "the legacy source", not "the mainframe", except where they mean exactly the mainframe. - The tagline on the header and in `reframe --help`: "From legacy source to reviewed requirements, business rules and a design to build from". `reframe run`'s help and the guided run ask for the legacy source, and say AWS Transform is for mainframe source. The published reports' index speaks of legacy assessments. - The package speaks of a modernized legacy application. A mainframe's mechanics (VSAM, CICS, JCL, COMMAREA) are named as an example, not as the only kind. START-HERE.md names the stack it was made from (for example "Java and JSP, java"), and its data contracts are copybooks, tables or entities. - The README says what each family gets in one table: the tools, how the design reads screens, flow and data, and what is proven (end to end for the mainframe; offline for Java, .NET and PHP; not yet for the rest). Its roadmap says release 1.1 is built and tested offline, with live acceptance next. - The guide has a section on what Reframe reads for each stack: the mainframe as it is, then Java, .NET, web scripts and the rest, and a codebase with no screens. - docs/cli.md and the help image (docs/images/cli-help.svg, regenerated at the same width) show the new help. Every Markdown link and anchor in the README, the guide and the command reference resolves. Prepared with AI assistance. --- README.md | 21 ++- docs/cli.md | 4 +- docs/guide.md | 33 ++++ docs/images/cli-help.svg | 308 ++++++++++++++++----------------- src/reframe/core/cli.py | 6 +- src/reframe/core/guide.py | 2 +- src/reframe/core/ui.py | 2 +- src/reframe/design/handover.py | 6 +- src/reframe/design/package.py | 13 +- src/reframe/report/pages.py | 2 +- 10 files changed, 220 insertions(+), 177 deletions(-) diff --git a/README.md b/README.md index 9ff021e1..a15998a6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@

    From legacy source to reviewed requirements, business rules and a design to build from.
    - Tested end to end on mainframe COBOL and CICS. On other languages, Claude's assessment and the reconciliation should work, untested. + Tested end to end on mainframe COBOL and CICS. Java, .NET and PHP are tested offline, with live runs to come.

    @@ -43,10 +43,17 @@ Reframe reads a legacy codebase and tells you, in plain words a business can review, what it does. It assesses the code with Claude's [code-modernization plugin](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-modernization), and with AWS Transform as well if you have it, then checks every business rule against the source code itself. From that it designs the modern application, down to a package an AI coding tool can build from. -| Codebase | What runs | Tested | -|---|---|---| -| **Mainframe:** COBOL, JCL, CICS, BMS | Everything: Claude's assessment and AWS Transform's, the reconciliation against the code, the design and the package | **Yes**, end to end on AWS's CardDemo | -| **Other languages:** Java, .NET, PHP, Python, C and more | With Claude only, since AWS Transform writes requirements only for the mainframe. The assessment and the reconciliation should work: Claude's plugin reads any language. The design reads screens, flows and data definitions from mainframe sources only, so it stops on other codebases for now | **No.** Full support is planned ([the 1.1 specification](docs/any-legacy.md)) | +Reframe works out what the codebase is first, its *stack profile*, and picks its tools and readers from it: + +| Family | Tools | How the design reads screens, flow and data | Proven | +|---|---|---|---| +| **Mainframe:** COBOL, PL/I, JCL, CICS, BMS, IMS | Claude's assessment and AWS Transform's, reconciled | Exact readers with no model: BMS maps, CICS transfers and definitions (CSD or resource-builder YAML), copybooks | **End to end** on AWS's CardDemo | +| **Java:** Java, JSP, JSF, Groovy, Kotlin | Claude only: AWS Transform writes requirements only for the mainframe | The general reader: views, fields and actions by a checked Claude step; links from routes and patterns; SQL DDL with no model, entities by a checked step | Offline, on small fixtures | +| **.NET:** C#, VB.NET, ASP.NET, Razor | Claude only | The general reader, with the MVC conventions | Offline, on small fixtures | +| **Web scripts:** PHP, Perl, Ruby, Python, classic ASP | Claude only | The general reader | Offline, on small fixtures | +| **Front end, native, 4GL, mixed** | Claude only | The general reader | **Not yet:** they run, unproven | + +A codebase with no screens (a batch system, a service or a library) gets its specifications, golden datasets, package and backlog without journeys, screens or a prototype. Live runs on two codebases beyond the mainframe come next ([the 1.1 specification](docs/any-legacy.md)). It is for modernization teams, architects and the business people who have to say "yes, that is what the system does" before anything is rebuilt. @@ -221,12 +228,12 @@ The figures are from live runs and are recorded in [docs/acceptance.md](docs/acc | [How to run Reframe](docs/how-to-run.md) | One page from install to handover | | [The guide](docs/guide.md) | Every step in detail: the guided run, Claude only, results, reviews, the reconciliation, the design, sharing and teardown | | [Commands](docs/cli.md) | Every command, option and example | -| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md) | +| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md), [any legacy codebase](docs/any-legacy.md) | | [The plan](docs/plan.md) | Every story, with what done means and the results | ## Roadmap -- **Beyond the mainframe (1.1):** any legacy codebase Claude's plugin reads (Java, .NET, PHP and more), with Claude only, and screens, flows and data contracts read for each stack ([the specification](docs/any-legacy.md)). +- **Beyond the mainframe (1.1):** built and tested offline: the stack profile, Claude-only runs by family, the reconciliation in the stack's words, and screens, flows, data contracts and "runs as" read for each stack. Live acceptance on two codebases comes next ([the specification](docs/any-legacy.md)). - **Proof at scale:** a codebase several times CardDemo's size, and a mainframe expert's own check of the audit. - **Later:** a replacement order from the specifications, real legacy outputs under GnuCOBOL, and Claude on Amazon Bedrock, live ([docs/plan.md](docs/plan.md)). diff --git a/docs/cli.md b/docs/cli.md index 89dab517..d1b7ecc5 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -94,11 +94,11 @@ Every command acts on your latest run; add `--run ` for another one. The ### `reframe run` -Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown. +Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown. | Option | What it does | |---|---| -| `--source ` | the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up | +| `--source ` | the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up | | `--profile ` | the AWS CLI profile to sign in with (default: the one saved by the guided setup) | | `--ref ` | for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD) | | `--mode autonomous\|interactive` | autonomous: Reframe answers AWS and records why; interactive: answer each question with reframe answer | diff --git a/docs/guide.md b/docs/guide.md index 4c06d2cd..08d63a46 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -5,6 +5,7 @@ Everything about running Reframe, step by step. Start with [How to run Reframe]( - [The home screen](#the-home-screen) - [Run an assessment: the guided way](#run-an-assessment-the-guided-way) - [Bringing source from a mainframe](#bringing-source-from-a-mainframe) +- [What Reframe reads for each stack](#what-reframe-reads-for-each-stack) - [Claude only, with no AWS](#claude-only-with-no-aws) - [If a run stops](#if-a-run-stops) - [Results](#results) @@ -168,6 +169,38 @@ A Git repository of the application, like CardDemo's, is the easiest source. Cod Where the check finds something, fix the package and start a new run, or go ahead knowing what AWS Transform will leave out. +## What Reframe reads for each stack + +After the snapshot, Reframe works out what the codebase is, with no model, and records it in `stack-profile.json` in the run folder: +- its languages, by file and by line; +- its family: the one that carries more than half the lines; +- what it has, with the files that show it: screens, routes, jobs and data. + +`reframe status` shows it, and so do the reviews. `reframe run --legacy ` overrides the family. For a local source, the guided run shows the profile before it starts, and asks only when no family carries most of the code. + +### Mainframe + +As in the rest of this guide: +- Both assessments, AWS Transform's and Claude's, reconciled. +- The exact readers, with no model: BMS maps for the screens, CICS transfers and definitions for the flow (a CSD extract or IBM's resource-builder YAML), and copybooks for the data contracts. +- The prompts speak of COBOL, PERFORM, CALL and copybooks. + +### Java, .NET, web scripts and the rest + +AWS Transform writes requirements only for mainframe code. So these runs are Claude only (`reframe run --tools claude`): Reframe refuses `--tools both` or `aws` before it creates anything, and the guided run does not offer AWS Transform. + +- **Programs** are source files, named by their path, so two `OrderService.java` files in different folders stay apart. +- **The reconciliation** speaks of the stack's languages, and of following a call, an include, an import or an inherited method. Every cited line is still checked against the snapshot. +- **Screens:** the general reader reads the views, pages and forms the profile found. A Claude step lists each screen's fields and actions; Reframe checks every line it cites, asks again once with the reasons, and otherwise keeps the screen with no fields. +- **Flow:** links are read from patterns with no model: an href, a form's action, a redirect, Spring and JAX-RS route annotations, Stripes' `@UrlBinding`, the ASP.NET MVC conventions, and a script page's own path. A checked Claude step settles the rest; what fails twice stays open, on the flow page. +- **Data contracts:** `CREATE TABLE` in SQL DDL, read with no model. Entity classes (JPA, Entity Framework) by a checked Claude step. +- **Runs as:** online when the rules are in code behind a screen; a scheduled job when a job definition (cron, Quartz, Spring Batch, `@Scheduled`, Windows tasks) runs them; a service when only routes reach them; a library otherwise. +- **Legacy screens** are shown as their fields and actions, citing the view's lines. The old page is not drawn. + +### A codebase with no screens + +A batch system, a service or a library gets its final specifications, golden datasets, package and backlog. The journeys, modern screens and prototype are left out, and the design page says why. + ## Claude only, with no AWS No AWS account, or no AWS Transform? Run Reframe with Claude only ([release 1.0](release-1.md), section 2). It needs Git, [Claude Code](https://docs.anthropic.com/en/docs/claude-code) signed in, and the code-modernization plugin, which Reframe fetches itself. Claude signs in with your Claude subscription (the default), an Anthropic API key (`--auth api-key`, with `ANTHROPIC_API_KEY` set), or Amazon Bedrock (`--auth bedrock --profile --region `, the profile used for Bedrock only, or `AWS_BEARER_TOKEN_BEDROCK`). diff --git a/docs/images/cli-help.svg b/docs/images/cli-help.svg index b82185c2..ad53e324 100644 --- a/docs/images/cli-help.svg +++ b/docs/images/cli-help.svg @@ -19,325 +19,325 @@ font-weight: 700; } - .terminal-4233349274-matrix { + .terminal-612813835-matrix { font-family: Fira Code, monospace; font-size: 20px; line-height: 24.4px; font-variant-east-asian: full-width; } - .terminal-4233349274-title { + .terminal-612813835-title { font-size: 18px; font-weight: bold; font-family: arial; } - .terminal-4233349274-r1 { fill: #68a0b3 } -.terminal-4233349274-r2 { fill: #c5c8c6 } -.terminal-4233349274-r3 { fill: #398280;font-weight: bold } -.terminal-4233349274-r4 { fill: #c5c8c6;font-weight: bold } -.terminal-4233349274-r5 { fill: #325e5d;font-weight: bold } -.terminal-4233349274-r6 { fill: #398280 } -.terminal-4233349274-r7 { fill: #868887 } + .terminal-612813835-r1 { fill: #68a0b3 } +.terminal-612813835-r2 { fill: #c5c8c6 } +.terminal-612813835-r3 { fill: #398280;font-weight: bold } +.terminal-612813835-r4 { fill: #c5c8c6;font-weight: bold } +.terminal-612813835-r5 { fill: #325e5d;font-weight: bold } +.terminal-612813835-r6 { fill: #398280 } +.terminal-612813835-r7 { fill: #868887 } - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - reframe --help + reframe --help - + - - ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ -││ -│REFRAME│ -│From mainframe source to reviewed requirements, business rules and a design to build from│ -│Prerequisites  →  Sign in  →  Source  →  AWS Transform and Claude  →  Review  →  Reconcile  →  Design  →│ -│Share│ -││ -╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯ - -Commands -Command          What it does                                                                             -────────────────────────────────────────────────────────────────────────────────────────────────────────────── -reframe run      Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools      -claude, no AWS): with no options, a guided run that checks and sets up everything first; -the AWS resources stay until reframe teardown                                            -reframe setup    Check and set up the prerequisites and the AWS sign-in, without starting a run           -reframe status   The run's stage, the job's plan steps, any waiting question and the next step            -reframe events   The run's event log                                                                      -reframe answer   Show AWS's waiting question, or answer it                                                -reframe resume   Continue a run that stopped; nothing with a receipt is repeated                          -reframe report   Build the HTML report from the run's downloads again                                     -reframe claude   The Claude assessment: assess the same snapshot with Claude's code-modernization plugin, -show it in the same business review, load its graph into the run's Neptune cluster, and  -compare it with AWS Transform's results                                                  -reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude   -only, every rule) against the source code, with evidence Reframe checks, then write      -recommended requirements, one SME list and the reconciliation page; needs the run's      -assessments done, and no AWS resources                                                   -reframe review   Read the review downloads in a folder and show each reviewer's coverage, sign-offs and   -where reviewers disagree; runs nothing, and the next reframe reconcile --context with    -the same folder combines them                                                            -reframe export   Write a run's reconciled results as one Excel workbook: domains, functions,              -capabilities, requirements, business rules, decision tables, open questions and the SME  -list, with the reviewers' marks; runs nothing                                            -reframe design   The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,   -final specifications and the AI-DLC package, from the reconciled results; a round redoes -only what new context touches                                                            -reframe compare  Build the page comparing AWS Transform's and Claude's results again                      -reframe publish  Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder  -others can open, upload the run's source, results and reports to your account's private  -bucket, or publish the copy to a GitHub Pages site                                       -reframe reports  The reports published to your AWS account: list them, open one with your AWS sign-in, or -remove the bucket                                                                        -reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them    - -Examples -reframe                                              the home screen: your runs, the next step and a menu -reframe run                                          a guided run: checks the prerequisites, the AWS      -sign-in and the source, then starts                  -reframe run --source <folder | file.zip | github-url>start straight away, with no questions               -reframe run --tools claude --source <source>         Claude only: no AWS account, nothing to tear down    -reframe status                                       where the latest run is, and what to do next         -reframe answer                                       AWS's waiting question, in interactive mode          -reframe report --open                                open the business review in the browser              -reframe claude                                       the Claude assessment: the same snapshot, assessed   -with Claude as well                                  -reframe compare --open                               open the page comparing AWS Transform and Claude     -reframe export --to xlsx                             the reconciled requirements and business rules as an -Excel workbook                                       -reframe design --open                                the design: screens, journeys, the prototype, final  -specifications and the AI-DLC package                -reframe publish --to aws                             upload the run's source, results and cleaned reports -to your account's private bucket                     -reframe reports                                      list the published reports; reframe reports open     -<project> opens the latest                           -reframe teardown                                     remove the AWS resources the run created             - -Options ---version               show program's version number and exit                                            --h, --help              this help                                                                         -reframe <command> --help shows a command's options. + + ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ +││ +│REFRAME│ +│From legacy source to reviewed requirements, business rules and a design to build from│ +│Prerequisites  →  Sign in  →  Source  →  AWS Transform and Claude  →  Review  →  Reconcile  →  Design  →│ +│Share│ +││ +╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯ + +Commands +Command          What it does                                                                             +────────────────────────────────────────────────────────────────────────────────────────────────────────────── +reframe run      Assess legacy source with Claude, and mainframe source with AWS Transform beside it      +(--tools claude: Claude only, no AWS): with no options, a guided run that checks and     +sets up everything first; the AWS resources stay until reframe teardown                  +reframe setup    Check and set up the prerequisites and the AWS sign-in, without starting a run           +reframe status   The run's stage, the job's plan steps, any waiting question and the next step            +reframe events   The run's event log                                                                      +reframe answer   Show AWS's waiting question, or answer it                                                +reframe resume   Continue a run that stopped; nothing with a receipt is repeated                          +reframe report   Build the HTML report from the run's downloads again                                     +reframe claude   The Claude assessment: assess the same snapshot with Claude's code-modernization plugin, +show it in the same business review, load its graph into the run's Neptune cluster, and  +compare it with AWS Transform's results                                                  +reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude   +only, every rule) against the source code, with evidence Reframe checks, then write      +recommended requirements, one SME list and the reconciliation page; needs the run's      +assessments done, and no AWS resources                                                   +reframe review   Read the review downloads in a folder and show each reviewer's coverage, sign-offs and   +where reviewers disagree; runs nothing, and the next reframe reconcile --context with    +the same folder combines them                                                            +reframe export   Write a run's results for other tools: the reconciled results as one Excel workbook      +(xlsx), or the design's capabilities as a backlog to import into Jira or Azure DevOps,   +with acceptance criteria; runs nothing                                                   +reframe design   The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,   +final specifications and the AI-DLC package, from the reconciled results; a round redoes +only what new context touches                                                            +reframe compare  Build the page comparing AWS Transform's and Claude's results again                      +reframe publish  Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder  +others can open, upload the run's source, results and reports to your account's private  +bucket, or publish the copy to a GitHub Pages site                                       +reframe reports  The reports published to your AWS account: list them, open one with your AWS sign-in, or +remove the bucket                                                                        +reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them    + +Examples +reframe                                              the home screen: your runs, the next step and a menu +reframe run                                          a guided run: checks the prerequisites, the AWS      +sign-in and the source, then starts                  +reframe run --source <folder | file.zip | github-url>start straight away, with no questions               +reframe run --tools claude --source <source>         Claude only: no AWS account, nothing to tear down    +reframe status                                       where the latest run is, and what to do next         +reframe answer                                       AWS's waiting question, in interactive mode          +reframe report --open                                open the business review in the browser              +reframe claude                                       the Claude assessment: the same snapshot, assessed   +with Claude as well                                  +reframe compare --open                               open the page comparing AWS Transform and Claude     +reframe export --to xlsx                             the reconciled requirements and business rules as an +Excel workbook                                       +reframe design --open                                the design: screens, journeys, the prototype, final  +specifications and the AI-DLC package                +reframe publish --to aws                             upload the run's source, results and cleaned reports +to your account's private bucket                     +reframe reports                                      list the published reports; reframe reports open     +<project> opens the latest                           +reframe teardown                                     remove the AWS resources the run created             + +Options +--version               show program's version number and exit                                            +-h, --help              this help                                                                         +reframe <command> --help shows a command's options. diff --git a/src/reframe/core/cli.py b/src/reframe/core/cli.py index fac2d2a0..8c35d140 100644 --- a/src/reframe/core/cli.py +++ b/src/reframe/core/cli.py @@ -43,16 +43,16 @@ def _run_option(parser: argparse.ArgumentParser) -> None: def parser() -> argparse.ArgumentParser: from reframe.core.helptext import Parser - top = Parser(prog="reframe", description="Run an AWS Transform mainframe assessment end to end and bring back its requirements.") + top = Parser(prog="reframe", description="From legacy source to reviewed requirements, business rules and a design to build from: with Claude, and for mainframe code with AWS Transform beside it.") top.add_argument("--version", action="version", version=f"reframe {__version__}") commands = top.add_subparsers(dest="command", metavar="") def command(name: str, help: str) -> argparse.ArgumentParser: return commands.add_parser(name, help=help, description=help) - run = command("run", "Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no " + run = command("run", "Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no " "options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown") - run.add_argument("--source", help="the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked " + run.add_argument("--source", help="the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked " "and the prerequisites are assumed to be set up") run.add_argument("--profile", help="the AWS CLI profile to sign in with (default: the one saved by the guided setup)") run.add_argument("--ref", help="for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD)") diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py index db18d625..267ca206 100644 --- a/src/reframe/core/guide.py +++ b/src/reframe/core/guide.py @@ -184,7 +184,7 @@ def _reachable(url: str) -> str | None: def source() -> tuple[str, str | None] | None: from reframe.source.snapshot import URL ui.section("3 Source") - form = ui.choose("Where is the mainframe source?", [("A GitHub or Git URL", "https://github.com//"), + form = ui.choose("Where is the legacy source?", [("A GitHub or Git URL", "https://github.com//"), ("A local folder", "a Git checkout or a plain folder"), ("A local ZIP file", "")], setup.load_config().get("source_form") or 1) if form == 1: diff --git a/src/reframe/core/ui.py b/src/reframe/core/ui.py index d1a81bd8..15adc2c6 100644 --- a/src/reframe/core/ui.py +++ b/src/reframe/core/ui.py @@ -24,7 +24,7 @@ def header(subtitle: str = "AWS Transform · Claude · Reconciliation · Design") -> None: content = Text("REFRAME\n", style="bold bright_cyan") - content.append("From mainframe source to reviewed requirements, business rules and a design to build from\n", style="bold white") + content.append("From legacy source to reviewed requirements, business rules and a design to build from\n", style="bold white") content.append(STEPS, style="dim") console.print(Panel(content, border_style="cyan", padding=(1, 2), subtitle=subtitle)) diff --git a/src/reframe/design/handover.py b/src/reframe/design/handover.py index 7841f570..2e026f21 100644 --- a/src/reframe/design/handover.py +++ b/src/reframe/design/handover.py @@ -147,7 +147,7 @@ def facts(specs: list[dict[str, Any]], journeys: list[dict[str, Any]], programs: } -def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, form: str | None) -> str: +def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, form: str | None, legacy: str = "") -> str: where = WHERE[form] if form else "\n\n".join(f"**{k}**\n\n{v}" for k, v in WHERE.items()) + "\n" drafts = "\n".join(f" - {name}: {n} draft" for name, n in sorted(f["drafts"].items())) or " - None." proof = "\n".join(f" - {p['id']} {p['title']} ({p['criteria']} acceptance criteria; {p['status']}" @@ -155,11 +155,11 @@ def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, fo artifacts = ", ".join(f["artifacts"]) or "none" return f"""# Start here -This package was written by Reframe from {project}'s legacy source, its reconciled requirements and rules, and the reviewers' sign-offs. It holds what +This package was written by Reframe from {project}'s legacy source{" (" + legacy + ")" if legacy else ""}, its reconciled requirements and rules, and the reviewers' sign-offs. It holds what those settle. What only your team can give is marked `[FILL IN: ...]`. These steps make it ready for forward engineering. {where} -- Every form: `data-contracts.md` (the copybooks as typed records), `traceability.md` (every ID back to the legacy source) and `golden/` +- Every form: `data-contracts.md` (the copybooks, tables or entities as typed records), `traceability.md` (every ID back to the legacy source) and `golden/` (each capability's golden dataset, the cases the new system must answer as the legacy one does, and `compare.py`). ## 1. Copy the package diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py index fb3a0ff0..11819008 100644 --- a/src/reframe/design/package.py +++ b/src/reframe/design/package.py @@ -65,7 +65,7 @@ "Use synthetic data only; never copy production or personal data.", "Keep the copybook and field names in a comment or mapping, so the legacy data can be migrated and compared."]), "api": ("API", "Builds the services and scheduled jobs the capability runs as, from the design notes.", - ["Follow each design note; the mainframe mechanics (VSAM, CICS, JCL, COMMAREA) are not to be copied.", + ["Follow each design note; the legacy platform's mechanics (on a mainframe: VSAM, CICS, JCL, COMMAREA) are not to be copied.", "A capability that runs as a scheduled job becomes a job with the same inputs, outputs and failure handling.", "Name the rules and requirements each endpoint or job implements."]), "test-generation": ("Test generation", "Writes an automated test for every acceptance criterion, named by its ID.", @@ -393,7 +393,7 @@ def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str: def role_md(role: str) -> str: name, what, rules = ROLES[role] - return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized mainframe application.", + return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized legacy application.", "", what, "", "## Template", "", "For each task you take: read the task's requirements, rules and criteria by ID in the specification; " "do the work; name the IDs you implemented; list what you could not do and why.", "", "## Guardrails", ""] + [f"- {r}" for r in rules] + ["- The legacy source is read-only. Use synthetic data only.", "- A draft capability is confirmed with the owner before it is built.", ""] @@ -474,11 +474,11 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: tech = "# Tech\n\n## Target stack\n\n" + stack_md(stack, context.get("architecture", "")) + "\n" files: dict[str, str] = {} known = handover.facts(specs, journeys, programs or {}) - files["START-HERE.md"] = handover.start_here(known, project, stack, None) + files["START-HERE.md"] = handover.start_here(known, project, stack, None, context.get("legacy", "")) kept = [d for d in datasets.values() if d["cases"] or d["uncovered"]] comparer = Path(golden_compare.__file__).read_text() for form in FORMS: - files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form) + files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form, context.get("legacy", "")) files[f"{form}/data-contracts.md"] = contracts files[f"{form}/traceability.md"] = trace files[f"{form}/golden/README.md"] = golden.readme(kept) @@ -664,7 +664,10 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]: root = Path(tmp) / "package" inventory = (folder.load("design/screens.json") or {}).get("screens") or [] programs = {s["map"]: [p["name"] for p in s.get("programs") or []] for s in inventory} - ts = write(root, specs, books, stack, journeys, prototype, project, read_context(context), programs) + from reframe.source import profile + stack_profile = profile.of_run(folder) # START-HERE names the stack (docs/any-legacy.md, section 5.5) + told = {**read_context(context), "legacy": f"{stack_profile['words']['languages']}, {stack_profile.get('family', 'mainframe')}"} + ts = write(root, specs, books, stack, journeys, prototype, project, told, programs) problems = check(root, specs, ts) made = manifest(specs, ts, stack) same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root) diff --git a/src/reframe/report/pages.py b/src/reframe/report/pages.py index 11fbe75f..d19af073 100644 --- a/src/reframe/report/pages.py +++ b/src/reframe/report/pages.py @@ -122,5 +122,5 @@ def index(site: Path, pattern: str = "*/*/manifest.json", title: str = "Reframe "main{max-width:900px;margin:0 auto;padding:32px 24px}.muted{color:var(--muted)}" ".card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px 18px;margin-bottom:12px;" "text-decoration:none;color:var(--ink)}.card:hover{border-color:var(--accent)}.card h2{margin:0 0 4px;font-size:18px}.card p{margin:0;color:var(--muted)}" - "

    " + html.escape(title) + "

    Mainframe assessments published by Reframe, cleaned of the " + "

    " + html.escape(title) + "

    Legacy assessments published by Reframe, cleaned of the " "identifiers of the accounts that ran them. Each is model output, for people to review.

    " + cards + "
    \n") From 3142d06f7455e6ee12e179a9c64ff69e0114deb0 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 08:37:51 -0700 Subject: [PATCH 13/13] P4-12: risk and replacement order The design orders the capabilities for replacement, with no model (docs/pipeline-4.md, section 4 D11), and writes design/order.json with each place's wave and reason. - Three waves, from each capability's risk and what it touches (P3-24): read-only first (reporting only, or nothing on the list, and low risk); then updates (record updates, card or personal data); then money, security and audit, or any high-risk capability, last. - Within a wave: lower risk first, then final capabilities before drafts, then the specifications' own order. - A capability that shares a data contract or a screen with one already placed follows it at once, within its own wave. Sharing never pulls a money or security capability into an earlier wave. - Each place says why in words, for example "Money, security or audit, so last: it touches security; high risk." or "... Follows View an account: they share CVACT01Y." - The design page has an "Order of replacement" table linking each capability. The package's constitution replaces its placeholder line 6 with the rule and an "Order of replacement" list. Claude Code's tasks.md is in that order, and every form's tasks for a capability say where it comes and why. The package's data-contracts.md now speaks of copybooks, tables or entities (L1-06's contracts). Tests: the three waves and their reasons, the order within a wave, shared data and screens kept together, a shared contract never moving a capability to an earlier wave, and a whole design round's page, constitution and tasks in each form. Prepared with AI assistance. --- src/reframe/design/designpage.py | 6 +++ src/reframe/design/order.py | 77 ++++++++++++++++++++++++++++++++ src/reframe/design/package.py | 35 +++++++++++---- src/reframe/design/specs.py | 2 + tests/design/test_order.py | 77 ++++++++++++++++++++++++++++++++ 5 files changed, 188 insertions(+), 9 deletions(-) create mode 100644 src/reframe/design/order.py create mode 100644 tests/design/test_order.py diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py index 381aa9ef..66d7a931 100644 --- a/src/reframe/design/designpage.py +++ b/src/reframe/design/designpage.py @@ -169,6 +169,10 @@ def draw(folder, value: dict[str, Any]) -> Path: if stack else "Target stack: not given yet, so the data contracts show neutral types.") notes = " ".join(e(n) for n in value.get("stack_notes") or [] if stack) contracts = "".join(contract_block(x) for x in value["contracts"].values()) + placed = (folder.load("design/order.json") or {}).get("order") or [] + replacement = _table([f'{p["position"]}{e(p["title"])}{e(p["wave_name"])}' + f'{e(p["reason"])}' for p in placed], ["#", "Capability", "Wave", "Why here"]) if placed else \ + '

    None yet.

    ' contracts_how = ("The tables and entities the capabilities' code uses, as typed records: the tables read from the SQL DDL with no model, the " "entities by a Claude step whose every cited line Reframe checked." if any(x.get("kind") for x in value["contracts"].values()) else "The copybooks the capabilities' programs copy, as typed records, read from the source with no model.") @@ -196,6 +200,8 @@ def draw(folder, value: dict[str, Any]) -> Path:
    +

    Order of replacement

    From each capability's risk and what it touches, with no model: read-only first, then +updates, then money, security and audit; a capability that shares a data contract or a screen with one already placed follows it.

    {replacement} {''.join(body_parts)}

    Data contracts

    {contracts_how}

    {contracts}

    What the checks still found

      {problems}{more}
    diff --git a/src/reframe/design/order.py b/src/reframe/design/order.py new file mode 100644 index 00000000..a913f010 --- /dev/null +++ b/src/reframe/design/order.py @@ -0,0 +1,77 @@ +"""Pipeline 4, stage D11: the order of replacement (P4-12, docs/pipeline-4.md section 4 D11). No model. + +Each capability has a risk and the list of what it touches (P3-24: money, card data, personal data, security, audit, +record updates, reporting only). Reframe orders the capabilities for replacement in three waves: + +1. **Read-only:** it touches reporting only, or nothing on the list, and its risk is low: reports and inquiry screens. +2. **Updates:** it updates records or holds card or personal data, and touches no money, security or audit. +3. **Money, security and audit last:** it touches any of them, or its risk is high (a compliance rule). + +Within a wave, lower risk comes first, then final capabilities before drafts, then the specification's own order. A +capability that shares a data contract or a screen with one already placed follows it at once, so what shares data +and screens is replaced together. Each place says why, in words. + + design/order.json: {"order": [{"key", "position", "wave", "reason", "with"}], "waves": {...}} +""" + +from __future__ import annotations + +from typing import Any + +FILE = "design/order.json" +WAVES = {1: "read-only", 2: "updates", 3: "money, security and audit"} +LAST = {"money", "security", "audit"} +UPDATES = {"updates_records", "card_data", "personal_data"} +WORDS = {"money": "money", "card_data": "card data", "personal_data": "personal data", "security": "security", "audit": "audit", + "updates_records": "record updates", "reporting_only": "reporting only"} +RISK = {"low": 0, "": 1, "medium": 1, "high": 2} + + +def wave(s: dict[str, Any]) -> int: + touches = set(s.get("touches") or []) + if touches & LAST or s.get("risk") == "high": + return 3 + if touches & UPDATES or s.get("risk") == "medium": + return 2 + return 1 + + +def shared(a: dict[str, Any], b: dict[str, Any]) -> list[str]: + """The data contracts and screens two capabilities share.""" + books = {c["copybook"] for c in a.get("contracts") or []} & {c["copybook"] for c in b.get("contracts") or []} + screens = {x["id"] for x in a.get("screens") or []} & {x["id"] for x in b.get("screens") or []} + return sorted(books) + sorted(screens) + + +def why(s: dict[str, Any], w: int) -> str: + touches = [WORDS.get(t, t) for t in s.get("touches") or []] + what = f"it touches {', '.join(touches)}" if touches else "it touches nothing on the list" + risk = f"{s['risk']} risk" if s.get("risk") else "risk not rated" + lead = {1: "Read-only, so first", 2: "It changes data, so after the read-only capabilities", + 3: "Money, security or audit, so last"}[w] + return f"{lead}: {what}; {risk}." + + +def order(specs: list[dict[str, Any]]) -> dict[str, Any]: + """The replacement order of the specifications, each place with its wave and reason.""" + index = {s["key"]: n for n, s in enumerate(specs)} + base = sorted(specs, key=lambda s: (wave(s), RISK.get(s.get("risk") or "", 1), s.get("status") != "final", index[s["key"]])) + placed: list[dict[str, Any]] = [] + done: set[str] = set() + for s in base: + if s["key"] in done: + continue + queue: list[tuple[dict[str, Any], dict[str, Any] | None]] = [(s, None)] + while queue: + x, after = queue.pop(0) + if x["key"] in done: + continue + done.add(x["key"]) + w = wave(x) + reason = why(x, w) + if after: + reason += f" Follows {after['title']}: they share {', '.join(shared(x, after))}." + placed.append({"key": x["key"], "title": x["title"], "position": len(placed) + 1, "wave": w, "wave_name": WAVES[w], + "reason": reason, "with": after["key"] if after else ""}) + queue += [(y, x) for y in base if y["key"] not in done and wave(y) == w and shared(x, y)] + return {"order": placed, "waves": {WAVES[w]: sum(1 for p in placed if p["wave"] == w) for w in WAVES}} diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py index 11819008..7e9dedb2 100644 --- a/src/reframe/design/package.py +++ b/src/reframe/design/package.py @@ -346,8 +346,14 @@ def design_md(s: dict[str, Any], books: dict[str, Any]) -> str: "## Testing", "", f"Every acceptance criterion in requirements.md is a test named by its ID ({len(s['acceptance'])} in all)."]) +def order_line(s: dict[str, Any]) -> list[str]: + """Where the capability comes in the order of replacement (P4-12), and why; nothing when there is no order.""" + p = s.get("replacement") + return [f"**Order of replacement:** {p['position']} of {p['of']}, {p['wave_name']}. {p['reason']}", ""] if p else [] + + def tasks_md(s: dict[str, Any], ts: list[dict[str, Any]]) -> str: - return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + task_lines(s, ts, numbered=True)) + "\n" + return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + task_lines(s, ts, numbered=True)) + "\n" def spec_md(s: dict[str, Any], books: dict[str, Any]) -> str: @@ -381,7 +387,7 @@ def speckit_plan(s: dict[str, Any], books: dict[str, Any], stack: dict[str, Any] def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str: - out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), "", "Each task names the role that does it; the role files are in .claude/agents/.", ""] + out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + ["Each task names the role that does it; the role files are in .claude/agents/.", ""] for t in ts: out.append(f"- [ ] {t['id']} [{t['role']}] {md(t['title'])}. Requirements: {', '.join(t['requirements'])}" + (f". Rules: {', '.join(t['rules'])}" if t["rules"] else "") + (f". Criteria: {', '.join(t['criteria'])}" if t.get("criteria") else "") @@ -463,11 +469,17 @@ def traceability_md(specs: list[dict[str, Any]], ts: dict[str, list[dict[str, An def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: dict[str, Any] | None, journeys: list[dict[str, Any]], - prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None) -> dict[str, list[dict[str, Any]]]: + prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None, + replacement: dict[str, Any] | None = None) -> dict[str, list[dict[str, Any]]]: """Every form of the package under root. Returns the tasks by capability.""" + placed = {p["key"]: p for p in (replacement or {}).get("order") or []} + specs = [{**s, "replacement": {**placed[s["key"]], "of": len(placed)}} if s["key"] in placed else s for s in specs] + by_order = sorted(specs, key=lambda s: (s["replacement"]["position"] if s.get("replacement") else len(specs) + 1)) + ordered = [f"{s['replacement']['position']}. {s['id']} {md(s['title'])} ({s['replacement']['wave_name']}): {s['replacement']['reason']}" + for s in by_order if s.get("replacement")] datasets = {s["id"]: golden.dataset(s) for s in specs} ts = {s["id"]: tasks(s, datasets[s["id"]]) for s in specs} - contracts = "# Data contracts\n\nThe copybooks the capabilities' programs copy, as typed records, read from the legacy source.\n\n" + \ + contracts = "# Data contracts\n\nThe copybooks, tables or entities the capabilities' code uses, as typed records, read from the legacy source.\n\n" + \ "\n".join(contract_md(c) for c in books.values()) trace = traceability_md(specs, ts) product = product_md(specs, journeys, project, context.get("personas", ""), context.get("decisions", "")) @@ -512,8 +524,9 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: "## Conventions", ""] + conventions() + ["", "## House conventions", "", handover.house(context.get("style", "")), "", "## Skills", "", "In `.claude/skills/`: " + ", ".join(f"`{n}`" for n in handover.SKILLS) + ". Fill in their placeholders first; START-HERE.md says how.", "", "## Capabilities", "", index, ""]) - files["claude-code/tasks.md"] = "# Tasks\n\nBuild final capabilities first. Each task names its role and the IDs it implements.\n\n" + "\n\n".join( - f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n" + files["claude-code/tasks.md"] = "# Tasks\n\n" + ("Build the capabilities in the order of replacement below, from their risk and what they touch (P4-12). " + if ordered else "Build final capabilities first. ") + "Each task names its role and the IDs it implements.\n\n" + "\n\n".join( + f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(order_line(s) + task_lines(s, ts[s["id"]])) for s in by_order) + "\n" for s in specs: files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books) if has_ui: @@ -527,9 +540,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: "3. Every requirement, rule, acceptance criterion and task keeps its ID, so the build stays traceable to the legacy source (traceability.md).", "4. The target stack is the engineer's: " + (f"{stack['stack']}." if stack else "not given yet; nothing that depends on it is built until it is."), "5. Final capabilities (signed off) are built to as written; draft ones are confirmed with the owner first.", - "6. Order of replacement: final capabilities first; the risk-ranked order (P4-12) will replace this when it exists.", + ("6. Order of replacement: the order below, from each capability's risk and what it touches (P4-12): read-only first, then updates, then money, " + "security and audit; capabilities that share data or screens are built together. Draft ones are confirmed with the owner first." + if ordered else "6. Order of replacement: final capabilities first."), "7. A business rule is kept exactly; a historical artifact is carried only after asking.", "", "## Roles", ""] - + [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + ["", "## Technical context", "", handover.technical_context(stack), "", + + [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + (["", "## Order of replacement", ""] + ordered if ordered else []) + + ["", "## Technical context", "", handover.technical_context(stack), "", "## House conventions", "", handover.house(context.get("style", "")), "", "## Conventions", ""] + conventions()) + "\n" for role in ROLES: files[f"spec-kit/.claude/agents/{role}.md"] = role_md(role) @@ -667,7 +683,8 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]: from reframe.source import profile stack_profile = profile.of_run(folder) # START-HERE names the stack (docs/any-legacy.md, section 5.5) told = {**read_context(context), "legacy": f"{stack_profile['words']['languages']}, {stack_profile.get('family', 'mainframe')}"} - ts = write(root, specs, books, stack, journeys, prototype, project, told, programs) + from reframe.design import order + ts = write(root, specs, books, stack, journeys, prototype, project, told, programs, folder.load(order.FILE)) problems = check(root, specs, ts) made = manifest(specs, ts, stack) same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root) diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index 5773140e..fe9ca402 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -541,6 +541,8 @@ def one(item) -> None: "problems": batch_problems + schema_problems + found, "steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)} folder.save(FILE, value) + from reframe.design import order + folder.save(order.FILE, order.order(specs)) # the order of replacement (P4-12), from risk and what each touches value["full"] = specs value["contracts"] = books value["round"] = told diff --git a/tests/design/test_order.py b/tests/design/test_order.py new file mode 100644 index 00000000..3f45ce2a --- /dev/null +++ b/tests/design/test_order.py @@ -0,0 +1,77 @@ +"""P4-12: risk and replacement order (docs/pipeline-4.md, section 4 D11). Capabilities are ordered for replacement from +their risk and what they touch, read-only first and money, security and audit last, shared data and screens kept +together; the order and its reasons are on the design page and in the package's constitution and tasks.""" +import unittest +from pathlib import Path + +from reframe.design import order, pipeline +from tests.design.test_pipeline import RoundsTest + + +def cap(key, risk="", touches=(), books=(), screens=(), status="draft"): + return {"key": key, "title": key.title(), "risk": risk, "touches": list(touches), "status": status, + "contracts": [{"copybook": b} for b in books], "screens": [{"id": s} for s in screens]} + + +class OrderTest(unittest.TestCase): + def test_read_only_first_then_updates_then_money_security_and_audit(self): + found = order.order([cap("pay", "high", ["money"]), cap("report", "low", ["reporting_only"]), cap("update", "medium", ["updates_records"]), + cap("signon", "high", ["security"]), cap("inquiry", "low")]) + self.assertEqual([(p["key"], p["wave_name"]) for p in found["order"]], + [("report", "read-only"), ("inquiry", "read-only"), ("update", "updates"), + ("pay", "money, security and audit"), ("signon", "money, security and audit")]) + self.assertEqual(found["waves"], {"read-only": 2, "updates": 1, "money, security and audit": 2}) + first = found["order"][0]["reason"] + self.assertEqual(first, "Read-only, so first: it touches reporting only; low risk.") + self.assertIn("Money, security or audit, so last: it touches money; high risk.", found["order"][3]["reason"]) + + def test_within_a_wave_lower_risk_then_final_first(self): + found = order.order([cap("b", "medium", ["card_data"]), cap("a", "low", ["personal_data"], status="draft"), + cap("c", "low", ["personal_data"], status="final")]) + self.assertEqual([p["key"] for p in found["order"]], ["c", "a", "b"]) + + def test_shared_data_and_screens_follow_at_once(self): + found = order.order([cap("view", "low", books=["ACCT"]), cap("list", "low", screens=["S-LIST"]), cap("detail", "low", books=["ACCT"]), + cap("other", "low", screens=["S-LIST"])]) + self.assertEqual([p["key"] for p in found["order"]], ["view", "detail", "list", "other"]) + detail = next(p for p in found["order"] if p["key"] == "detail") + self.assertEqual(detail["with"], "view") + self.assertTrue(detail["reason"].endswith("Follows View: they share ACCT.")) + + def test_sharing_never_pulls_a_capability_into_an_earlier_wave(self): + found = order.order([cap("view", "low", books=["ACCT"]), cap("pay", "high", ["money"], books=["ACCT"]), cap("report", "low")]) + self.assertEqual([p["key"] for p in found["order"]], ["view", "report", "pay"]) + + +class InThePackageTest(RoundsTest): + """On the design fixture (sign-on, high risk for security; the account view, not rated): the page and the package.""" + + def test_the_order_on_the_page_and_in_the_package(self): + value = pipeline.run(self.folder, self.claude) + placed = self.folder.load(order.FILE)["order"] + self.assertEqual([p["key"] for p in placed], ["rec/Accounts/View#1", "rec/Access/SignOn#1"]) # security last + page = self.folder.path("outputs/design/index.html").read_text() + self.assertIn('

    Order of replacement

    ', page) + self.assertIn("Money, security or audit, so last: it touches security; high risk.", page) + root = Path(value["package"]["path"]) + constitution = (root / "spec-kit/.specify/memory/constitution.md").read_text() + self.assertIn("## Order of replacement", constitution) + self.assertIn("6. Order of replacement: the order below", constitution) + self.assertNotIn("will replace this when it exists", constitution) + tasks = (root / "claude-code/tasks.md").read_text() + self.assertLess(tasks.index("## VA-C01 View an account"), tasks.index("## SIG-C01 Sign on")) # the account view's tasks come first + self.assertIn("**Order of replacement:** 1 of 2, read-only. Read-only, so first: it touches nothing on the list; risk not rated.", tasks) + kiro = next((root / "kiro/.kiro/specs").glob("*sign*/tasks.md")).read_text() + self.assertIn("**Order of replacement:** 2 of 2, money, security and audit.", kiro) + speckit = next((root / "spec-kit/specs").glob("*sign*/tasks.md")).read_text() + self.assertIn("**Order of replacement:** 2 of 2", speckit) + + +def load_tests(loader, tests, pattern): + suite = loader.loadTestsFromTestCase(OrderTest) + suite.addTest(InThePackageTest("test_the_order_on_the_page_and_in_the_package")) + return suite + + +if __name__ == "__main__": + unittest.main()