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 bdde6f59..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 | @@ -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/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/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/cli.py b/src/reframe/core/cli.py index afb4ba68..8c35d140 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") @@ -42,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)") @@ -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..64232c0d 100644 --- a/src/reframe/core/commands/starting.py +++ b/src/reframe/core/commands/starting.py @@ -20,7 +20,12 @@ 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)) + 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") @@ -29,11 +34,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=legacy) 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 +50,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 +81,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 +96,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..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: @@ -211,6 +211,26 @@ def check_url(value: str) -> str | None: return str(Path(archive).expanduser().resolve()), 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 (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, 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 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)) + told = families[picked - 1] + return told, None if told == "mixed" else told + + # ---- 4 and 5. choices, summary, start ---------------------------------------------------------------- @@ -355,13 +375,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 +392,16 @@ def run(args) -> int: if picked_source is None: return 1 chosen, ref = picked_source + 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.") @@ -380,7 +411,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/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/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/designpage.py b/src/reframe/design/designpage.py index e8a0f032..381aa9ef 100644 --- a/src/reframe/design/designpage.py +++ b/src/reframe/design/designpage.py @@ -16,6 +16,7 @@ PAGE = "outputs/design/index.html" EXTRA = """ +.note{background:var(--card);border:1px solid var(--line);border-left:4px solid var(--warn);border-radius:8px;padding:10px 14px} .tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin:14px 0} .tile{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:10px 12px}.tile b{display:block;font-size:22px} .tile span{color:var(--muted);font-size:13px} @@ -148,8 +149,9 @@ def draw(folder, value: dict[str, Any]) -> Path: c, m = value["counts"], (modern.get("counts") or {}) how = ", ".join(f"{n} {h}" for h, n in (m.get("how") or {}).items() if n) stack = value.get("stack") or {} - tiles = [(len(inventory.get("screens") or []), "legacy screens"), (len(modern.get("screens") or []), "modern screens"), (len(journeys), "journeys"), - (m.get("mapped", 0), "legacy items mapped"), (c["capabilities"], "capabilities"), (c["final"], "final"), (c["draft"], "draft"), + left_out = modern.get("left_out") or "" # a codebase with no screens (L1-04) + tiles = ([] if left_out else [(len(inventory.get("screens") or []), "legacy screens"), (len(modern.get("screens") or []), "modern screens"), + (len(journeys), "journeys"), (m.get("mapped", 0), "legacy items mapped")]) + [(c["capabilities"], "capabilities"), (c["final"], "final"), (c["draft"], "draft"), (c["requirements"], "requirements"), (c["criteria"], "acceptance criteria"), (c["contracts"], "data contracts"), (c["gaps"], "decision table gaps"), (c["questions"], "open SME questions")] domains: dict[str, dict[str, list[dict[str, Any]]]] = {} @@ -167,11 +169,23 @@ 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 "")}

') + 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
-

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

-

The design

+{nav} +

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 @@ -183,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

""" target = folder.path(PAGE) 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..5709a1d3 --- /dev/null +++ b/src/reframe/design/general.py @@ -0,0 +1,459 @@ +"""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} + | {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())} + 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/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/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/package.py b/src/reframe/design/package.py index f90ac536..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.", @@ -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")]) @@ -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) @@ -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 @@ -661,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/design/pipeline.py b/src/reframe/design/pipeline.py index f1c4d961..44a399ed 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,33 +275,56 @@ 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()}) 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) - 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/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/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 faa0ed87..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]]: @@ -191,7 +217,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 +232,15 @@ 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 {} + 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 []} names = requirements.get("names") or {} found = [] @@ -234,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", "")), @@ -397,7 +432,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,12 +443,22 @@ 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) - 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 {} @@ -443,7 +489,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 @@ -491,7 +538,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 @@ -509,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/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)}

    " + 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") 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..78d06b2a --- /dev/null +++ b/src/reframe/source/profile.py @@ -0,0 +1,260 @@ +"""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 is_library(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 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: + 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 is_library(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}" + + +# ---- the stack's words in the prompts (L1-03, docs/any-legacy.md section 5.3) ------------------------------------------- + +MAINFRAME_REACH = ("a paragraph must be reached from the program's entry, and a program from a menu entry, a transaction, an XCTL, " + "LINK or CALL, or a job step that runs (not in a job whose job card has TYPRUN=SCAN, and not commented out)") +OTHER_REACH = ("a function or method must be reached from an entry point, and an entry point from a route, a page or form, a menu, " + "a call, an event or a scheduled job that runs (not commented out, and not left out of the build)") + + +def of_run(folder: Any) -> dict[str, Any]: + """The run's stack profile; a run from before release 1.1 is a mainframe run with the mainframe's words.""" + return folder.load(FILE) or {"family": "mainframe", "words": {"languages": "COBOL", **WORDS["mainframe"]}} + + +def in_words(text: str, stack: dict[str, Any]) -> str: + """A prompt written for the mainframe, in the stack's words. For the mainframe it is returned exactly as it is.""" + 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/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/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() diff --git a/tests/design/test_general.py b/tests/design/test_general.py new file mode 100644 index 00000000..740ac1dd --- /dev/null +++ b/tests/design/test_general.py @@ -0,0 +1,232 @@ +"""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) + 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"]) + 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()) + 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__": + unittest.main() diff --git a/tests/design/test_no_screens.py b/tests/design/test_no_screens.py new file mode 100644 index 00000000..6219b813 --- /dev/null +++ b/tests/design/test_no_screens.py @@ -0,0 +1,93 @@ +"""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.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() + 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() 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/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() diff --git a/tests/reconcile/test_stack_words.py b/tests/reconcile/test_stack_words.py new file mode 100644 index 00000000..49a2cd47 --- /dev/null +++ b/tests/reconcile/test_stack_words.py @@ -0,0 +1,112 @@ +"""L1-03: a reconciliation in the stack's words (docs/any-legacy.md, section 5.3). The prompts and the source files come +from the stack profile; the evidence check, the audit and the expert's pack work on a non-mainframe fixture; for the +mainframe every prompt is exactly as before.""" +import tempfile +import unittest +from pathlib import Path + +from reframe.reconcile import audit, decide, describe, expert, inputs +from reframe.source import profile +from tests import stacks +from tests.reconcile.test_audit import AuditTest, Judge + +PROMPTS = {"decide": decide.PROMPT, "describe": describe.PROMPT, "audit": audit.PROMPT, "expert": expert.GUIDE} + + +class WordsTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def stack(self, name): + return profile.profile_folder(stacks.write(Path(self.tmp.name) / name, stacks.FIXTURES[name])) + + def test_the_mainframe_prompts_are_exactly_as_before(self): + mainframe = self.stack("mainframe") + for name, text in PROMPTS.items(): + self.assertIs(profile.in_words(text, mainframe), text, name) + before = profile.of_run(type("F", (), {"load": lambda self, name: None})()) # a run from before the profile + self.assertIs(profile.in_words(decide.PROMPT, before), decide.PROMPT) + + def test_a_java_codebase_in_its_own_words(self): + java = self.stack("java") + text = profile.in_words(decide.PROMPT, java) + self.assertIn("business reviewers who do not read Java and JSP", text) + self.assertIn("follow a call, an include, an import or an inherited method if the decision depends on it", text) + self.assertIn("from the source files of a legacy system", text) + self.assertIn("an entry point from a route, a page or form", text) + for mainframe_word in ("PERFORM", "copybook", "COBOL", "XCTL", "TYPRUN", "job card"): + self.assertNotIn(mainframe_word, text) + for name in ("describe", "audit"): + self.assertNotIn("PERFORM", profile.in_words(PROMPTS[name], java), name) + self.assertNotIn("XCTL", profile.in_words(PROMPTS[name], java), name) + self.assertIn("C# and Razor", profile.in_words(decide.PROMPT, self.stack("dotnet"))) + # the business form of a rule stays as it is + self.assertIn('"WHEN , THE SHALL "', text) + + +class SourceFilesTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = stacks.write(Path(self.tmp.name), stacks.JAVA_WEB) + + def test_the_profiles_languages_each_file_standing_for_itself(self): + found = inputs.source_files(self.root, "java") + self.assertEqual(sorted(found), sorted(p.upper() for p in [ + "src/main/java/org/demo/shop/web/OrderController.java", "src/main/java/org/demo/shop/service/OrderService.java", + "src/main/java/org/demo/shop/model/Order.java", "src/main/java/org/demo/shop/jobs/NightlyReport.java", + "src/main/webapp/WEB-INF/jsp/orders/list.jsp", "src/main/webapp/WEB-INF/jsp/orders/new.jsp"])) # no vendor script, no pom + self.assertEqual(found["SRC/MAIN/JAVA/ORG/DEMO/SHOP/SERVICE/ORDERSERVICE.JAVA"], ["src/main/java/org/demo/shop/service/OrderService.java"]) + self.assertEqual(dict(inputs.source_files(self.root)), {"SCHEMA": ["src/main/resources/schema.sql"]}) # read as a mainframe: only its Db2-style DDL + + def test_the_evidence_check_is_unchanged(self): + self.assertEqual(decide.missing_evidence(["src/main/java/org/demo/shop/service/OrderService.java:13-15"], self.root), []) + self.assertEqual(decide.missing_evidence(["src/main/java/org/demo/shop/service/OrderService.java:300"], self.root), + ["src/main/java/org/demo/shop/service/OrderService.java:300"]) + + +class JavaAuditTest(AuditTest): + """The audit and the expert's pack on a run whose stack is Java.""" + + def setUp(self): + super().setUp() + legacy = self.folder.root / "claude" / "legacy" / "demo" + stacks.write(legacy, stacks.JAVA_WEB) + self.folder.save(profile.FILE, profile.profile_folder(legacy)) + + def test_the_audit_asks_in_the_stacks_words(self): + prompts = [] + + class Seeing(Judge): + def run(self, name, prompt, timeout=0, schema=None): + prompts.append(prompt) + return super().run(name, prompt, timeout, schema) + + judge = Seeing(self.root) + audit.run(self.folder, judges={"opus": "o"}, say=lambda *_: None, make_claude=lambda model: judge) + self.assertTrue(prompts) + self.assertTrue(all("follow a call, an include, an import or an inherited method where the rule depends on it" in p for p in prompts)) + self.assertFalse(any("PERFORM" in p for p in prompts)) + + def test_the_experts_pack_names_the_stack(self): + judge = Judge(self.root) + audit.run(self.folder, judges={"opus": "o", "sonnet": "s"}, say=lambda *_: None, make_claude=lambda model: judge) + out = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(out, ignore_errors=True)) + expert.pack(self.folder, out) + readme = (out / "README.md").read_text() + self.assertIn("The source is Java and JSP (java).", readme) + self.assertIn("The source is Java and JSP (java).", (out / "index.html").read_text()) + + +def load_tests(loader, tests, pattern): + suite = unittest.TestSuite() + for case in (WordsTest, SourceFilesTest): + suite.addTests(loader.loadTestsFromTestCase(case)) + suite.addTests(JavaAuditTest(name) for name in vars(JavaAuditTest) if name.startswith("test_")) + return suite + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/source/test_profile.py b/tests/source/test_profile.py new file mode 100644 index 00000000..29183ccb --- /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: 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), {}) + + 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..b4b2fd3b --- /dev/null +++ b/tests/stacks.py @@ -0,0 +1,318 @@ +"""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"; + } + + @GetMapping("/new") + public String form() { + return "orders/new"; + } + + @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"; + + public InvoiceProcessor processor() { + return new InvoiceProcessor(); + } +} +""", + "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") 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.""" + +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