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 0cd3b04b..08d63a46 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -4,6 +4,8 @@ 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)
@@ -142,6 +144,63 @@ By default each run creates its own Neptune Serverless graph in a private networ
To use a Neptune cluster you already have, pass `--graph existing` to choose from a list, or `--graph `. With no `--graph`, interactive mode lists the clusters in the region and asks. Reframe uses an existing cluster as it is and never changes or deletes it. It offers one only if it meets every need: available with an instance, Serverless, engine 1.4.5.1 or later, IAM authentication, encryption, subnets in two availability zones with an S3 gateway endpoint, a security group pair, and a bulk-loader role that can read the run's source bucket. For each cluster it rejects, it says why.
+## Bringing source from a mainframe
+
+A Git repository of the application, like CardDemo's, is the easiest source. Code taken from a mainframe usually comes as AWS Transform documents its source package, in [the AWS Transform user guide's page on mainframe source artifacts](https://docs.aws.amazon.com/transform/latest/userguide/transform-app-mainframe-source-artifacts.html). Reframe reads that package as it is: give `--source` the folder or the ZIP file.
+
+**The package.**
+- Put one folder per artifact type, for example `cobol/`, `jcl/`, `copybooks/`, `db2/`, `ims/`, `cics/` and `ca7/`. The names are AWS's examples; Reframe does not need them.
+- Use AWS Transform's extensions, in any case: `.cbl` (or `.cob`, `.cobol`), `.cpy`, `.bms`, `.jcl`, `.prc`, `.pl1`, `.asm`, `.csd`, `.dbd`, `.psb`, `.sql` and the others on AWS's page. A member downloaded with no extension, or as `.txt`, is classed by its content, as AWS Transform classes it.
+- Keep every file in one encoding. Files transferred in text mode arrive in ASCII or UTF-8. AWS Transform asks for one encoding across the files, or its documentation can have empty sections.
+
+**The system extracts** come from the running system, not the source library. AWS's page gives the job for each. Each is optional, and Reframe reports which are there:
+- the catalog listing, from IDCAMS `LISTCAT`;
+- the CICS definitions, from `DFHCSDUP` `EXTRACT`, as a `.csd` file. The design's flow reads its `DEFINE TRANSACTION` statements, and also IBM's CICS resource-builder YAML (`resourceDefinitions`), where a codebase keeps its definitions that way;
+- the IMS definitions, as IMS Stage 1 from `DFSURDD0`, `.ims`;
+- the CA-7 job reports, from `LJOB`, `.ca7`.
+
+**SMF data** goes in its own folder in S3, not with the source. AWS Transform uses it for its activity analysis, which Reframe does not run, so leave it out of what you give `--source`.
+
+**The package check.** After the snapshot, and before anything is uploaded, Reframe writes `package-check.json` in the run folder. It changes nothing in the source. `reframe status` shows it, and the reviews show it at the foot of the overview. It lists:
+- the files whose extension AWS Transform's table does not name, and those among them that look like mainframe source all the same, for example JCL kept as a template;
+- the files whose content is not what their extension says, with what AWS Transform will take them as. IMS DBD and PSB macros kept as `.asm` are taken as Assembler;
+- the files that are not text, and the encodings of the source files;
+- which system extracts are present.
+
+Where the check finds something, fix the package and start a new run, or go ahead knowing what AWS Transform will leave out.
+
+## 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`).
@@ -423,7 +482,7 @@ This is optional too. It puts the cleaned copy on the repository's `gh-pages` br
| Folder | What it does |
|---|---|
| `src/reframe/core/` | The CLI, the run folder and its change records, preflight, the stage pipeline and teardown |
-| `src/reframe/source/` | Taking the source snapshot and uploading it to S3 |
+| `src/reframe/source/` | Taking the source snapshot, the table of source kinds, the package check, and uploading the snapshot to S3 |
| `src/reframe/infrastructure/` | The Terraform roots and modules, the Neptune cluster checks and the network clean-up |
| `src/reframe/transform/` | AWS Transform: the MCP client, the workspace and connector, the job driver, answering questions, retrieval |
| `src/reframe/claude/` | The Claude assessment: the pinned plugin, running Claude Code headless, the workspace, the plugin's steps, retrieval, the generated requirements and the graph load |
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 26765f24..368e4772 100644
--- a/src/reframe/core/commands/reading.py
+++ b/src/reframe/core/commands/reading.py
@@ -37,6 +37,15 @@ 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, profile
+ stack = folder.load(profile.FILE)
+ if stack:
+ ui.state("Stack", profile.summary(stack), "")
+ checked = folder.load(package_check.FILE)
+ 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)
if state.get("graph"):
graph = state["graph"]
ui.state("Neptune", "existing cluster " + graph["name"] if graph["kind"] == "existing" else "a new graph", "")
diff --git a/src/reframe/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/contracts.py b/src/reframe/design/contracts.py
index e03b97a0..5a114dc9 100644
--- a/src/reframe/design/contracts.py
+++ b/src/reframe/design/contracts.py
@@ -33,23 +33,22 @@
# ---- copybooks ---------------------------------------------------------------------------------------------------------
def copybooks(legacy: Path) -> dict[str, Path]:
- """Data copybooks by name: every .cpy file wherever it is (some codebases keep them beside the programs), and the files
- without an extension in cpy folders. The screen copybooks are left out: those in a cpy-bms folder, and those named
- after a BMS mapset in the snapshot."""
- files = sorted(p for p in legacy.rglob("*") if p.is_file())
- maps = {p.stem.upper() for p in files if p.suffix.lower() == ".bms"}
+ """Data copybooks by name: every copybook wherever it is (some codebases keep them beside the programs), by its
+ extension or its content, and the files without an extension in cpy folders (reframe.source.kinds). The screen
+ copybooks are left out: those in a cpy-bms folder, and those named after a BMS mapset in the snapshot."""
+ from reframe.source import kinds
+ maps = {p.stem.upper() for p in kinds.files(legacy, "bms")}
found: dict[str, Path] = {}
- for p in files:
- folder = p.parent.name.lower()
- if "bms" in folder or p.stem.upper() in maps:
+ for p in kinds.copybooks(legacy):
+ if "bms" in p.parent.name.lower() or p.stem.upper() in maps:
continue
- if p.suffix.lower() == ".cpy" or (p.suffix == "" and folder.startswith("cpy")):
- found.setdefault(p.stem.upper(), p)
+ found.setdefault(p.stem.upper(), p)
return found
def programs(legacy: Path) -> dict[str, Path]:
- return {p.stem.upper(): p for p in sorted(legacy.rglob("*")) if p.is_file() and p.suffix.lower() in (".cbl", ".cob")}
+ from reframe.source import kinds
+ return {p.stem.upper(): p for p in kinds.files(legacy, "cobol")}
def copied(text: str) -> list[str]:
diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py
index e8a0f032..66d7a931 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,27 @@ def draw(folder, value: dict[str, Any]) -> Path:
if stack else "Target stack: not given yet, so the data contracts show neutral types.")
notes = " ".join(e(n) for n in value.get("stack_notes") or [] if stack)
contracts = "".join(contract_block(x) for x in value["contracts"].values())
+ placed = (folder.load("design/order.json") or {}).get("order") or []
+ replacement = _table([f'
' for p in placed], ["#", "Capability", "Wave", "Why here"]) if placed else \
+ '
None yet.
'
+ contracts_how = ("The tables and entities the capabilities' code uses, as typed records: the tables read from the SQL DDL with no model, the "
+ "entities by a Claude step whose every cited line Reframe checked." if any(x.get("kind") for x in value["contracts"].values()) else
+ "The copybooks the capabilities' programs copy, as typed records, read from the source with no model.")
+ nav = (f'
' 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.
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
@@ -182,8 +200,10 @@ def draw(folder, value: dict[str, Any]) -> Path:
+
Order of replacement
From each capability's risk and what it touches, with no model: read-only first, then
+updates, then money, security and audit; a capability that shares a data contract or a screen with one already placed follows it.
{replacement}
{''.join(body_parts)}
-
Data contracts
The copybooks the capabilities' programs copy, as typed records, read from the source with no model.
{contracts}
+
Data contracts
{contracts_how}
{contracts}
What the checks still found
{problems}{more}
"""
target = folder.path(PAGE)
diff --git a/src/reframe/design/flow.py b/src/reframe/design/flow.py
index b9e577d5..07ca1858 100644
--- a/src/reframe/design/flow.py
+++ b/src/reframe/design/flow.py
@@ -2,7 +2,8 @@
Read from the source with no model, each link citing its lines:
-- transaction to program, from the CSD (DEFINE TRANSACTION ... PROGRAM);
+- transaction to program, from the CSD (DEFINE TRANSACTION ... PROGRAM, as DFHCSDUP writes it) or from IBM's CICS
+ resource-builder YAML (`resourceDefinitions`, each `transaction` naming its `program`) (MP-02);
- program to program, from EXEC CICS XCTL and LINK, and RETURN TRANSID to another transaction;
- a target held in a variable is resolved from the program's MOVEs into it and the VALUE clauses of the program and the
copybooks it copies; a target taken from a table, such as a menu's option table, is resolved to every program in the
@@ -136,8 +137,13 @@ def _first(pattern: str, text: str, default: str = "") -> str:
def _copybooks(legacy: Path) -> dict[str, Path]:
- return {p.stem.upper(): p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() in (".cpy", "")
- and p.parent.name.lower().startswith("cpy")}
+ """Copybooks by name, from Reframe's table of source kinds (MP-01): wherever they are, by extension or content. Those in
+ a folder whose name starts with `cpy` come first, as before, when two share a name."""
+ from reframe.source import kinds
+ found: dict[str, Path] = {}
+ for p in sorted(kinds.copybooks(legacy), key=lambda p: (not p.parent.name.lower().startswith("cpy"), p.as_posix())):
+ found.setdefault(p.stem.upper(), p)
+ return found
def read_program(path: Path, legacy: Path, copybooks: dict[str, Path]) -> Program:
@@ -230,15 +236,54 @@ def resolve(program: Program, expr: str, depth: int = 0) -> list[dict[str, Any]]
# ---- the flow ----------------------------------------------------------------------------------------------------------
+CICS_NAME = r"([A-Za-z0-9$#@][^\s()]{0,7})" # a CICS resource name: letters, digits and the national characters $ # @, up to 8
+
+
def transactions(legacy: Path) -> list[dict[str, Any]]:
+ """Every transaction with its program, each citing the line that defines it: from the CSD's DEFINE statements and from
+ IBM's CICS resource-builder YAML. A transaction defined twice keeps every definition; the flow uses the first."""
+ from reframe.source import kinds
found = []
- for path in sorted(p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() == ".csd"):
+ for path in kinds.files(legacy, "csd"):
text = path.read_text(errors="replace")
- for m in re.finditer(r"DEFINE\s+TRANSACTION\((\w+)\)(.*?)(?=\bDEFINE\b|\Z)", text, re.S | re.I):
- program = re.search(r"\bPROGRAM\((\w+)\)", m.group(2), re.I)
+ for m in re.finditer(r"DEFINE\s+TRANSACTION\(\s*" + CICS_NAME + r"\s*\)(.*?)(?=\bDEFINE\b|\Z)", text, re.S | re.I):
+ program = re.search(r"\bPROGRAM\(\s*" + CICS_NAME + r"\s*\)", m.group(2), re.I)
if program:
found.append({"transaction": m.group(1).upper(), "program": program.group(1).upper(),
"lines": [f"{path.relative_to(legacy).as_posix()}:{text[:m.start()].count(chr(10)) + 1}"]})
+ for path in sorted(p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() in (".yaml", ".yml")):
+ found += resource_builder(path, legacy)
+ return found
+
+
+def resource_builder(path: Path, legacy: Path) -> list[dict[str, Any]]:
+ """The transactions in one file of IBM's CICS resource-builder YAML: a top-level `resourceDefinitions` list whose items
+ are `transaction:` mappings with a `name` and a `program`. Any other YAML gives nothing."""
+ import yaml
+ text = path.read_text(errors="replace")
+ if "resourceDefinitions" not in text:
+ return []
+ try:
+ root = yaml.compose(text, Loader=yaml.SafeLoader)
+ except yaml.YAMLError:
+ return []
+ if not isinstance(root, yaml.MappingNode):
+ return []
+ found = []
+ for key, value in root.value:
+ if key.value != "resourceDefinitions" or not isinstance(value, yaml.SequenceNode):
+ continue
+ for item in value.value:
+ if not isinstance(item, yaml.MappingNode):
+ continue
+ for kind, body in item.value:
+ if kind.value != "transaction" or not isinstance(body, yaml.MappingNode):
+ continue
+ fields = {k.value: v.value for k, v in body.value if isinstance(v, yaml.ScalarNode)}
+ name, program = str(fields.get("name") or ""), str(fields.get("program") or "")
+ if re.fullmatch(CICS_NAME, name) and re.fullmatch(CICS_NAME, program):
+ found.append({"transaction": name.upper(), "program": program.upper(),
+ "lines": [f"{path.relative_to(legacy).as_posix()}:{kind.start_mark.line + 1}"]})
return found
@@ -273,8 +318,8 @@ def _branch(program: Program, line: int) -> tuple[int, int]:
def flow(legacy: Path, screens: dict[str, Any]) -> dict[str, Any]:
copybooks = _copybooks(legacy)
- programs = {p.stem.upper(): read_program(p, legacy, copybooks) for p in sorted(legacy.rglob("*"))
- if p.is_file() and p.suffix.lower() in (".cbl", ".cob")}
+ from reframe.source import kinds
+ programs = {p.stem.upper(): read_program(p, legacy, copybooks) for p in kinds.files(legacy, "cobol")}
by_tran: dict[str, dict[str, Any]] = {}
trans = transactions(legacy)
for t in trans:
diff --git a/src/reframe/design/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 "") + "
"
+ ('
By
Goes to
Lines
' + "".join(rows) + "
" 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/inventory.py b/src/reframe/design/inventory.py
index 6e517a73..ce71923a 100644
--- a/src/reframe/design/inventory.py
+++ b/src/reframe/design/inventory.py
@@ -19,9 +19,6 @@
from pathlib import Path
from typing import Any
-BMS_SUFFIXES = (".bms",)
-COBOL_SUFFIXES = (".cbl", ".cob")
-COPY_SUFFIXES = (".cpy", "")
LINES, COLUMNS = 24, 80
@@ -310,10 +307,6 @@ def handled_keys(text: str, program: str) -> list[dict[str, Any]]:
# ---- the whole snapshot ------------------------------------------------------------------------------------------------
-def _files(root: Path, suffixes: tuple[str, ...]) -> list[Path]:
- return sorted(p for p in root.rglob("*") if p.is_file() and p.suffix.lower() in suffixes)
-
-
def code_only(text: str) -> str:
"""A fixed-format COBOL source with its comment lines (* or / in column 7) blanked."""
return "\n".join("" if len(line) > 6 and line[6] in "*/" else line for line in text.splitlines())
@@ -326,13 +319,14 @@ def _copies(text: str) -> set[str]:
def inventory(legacy: Path) -> dict[str, Any]:
"""Every map in the snapshot with its fields, problems and function keys; the programs that use each mapset."""
rel = lambda p: p.relative_to(legacy).as_posix() # noqa: E731
- symbolic = {p.stem.upper(): p for p in _files(legacy, (".cpy",)) if "bms" in p.parent.name.lower()}
+ from reframe.source import kinds
+ symbolic = {p.stem.upper(): p for p in kinds.copybooks(legacy) if "bms" in p.parent.name.lower()}
programs = {}
- for p in _files(legacy, COBOL_SUFFIXES):
+ for p in kinds.files(legacy, "cobol"):
text = p.read_text(errors="replace")
programs[p.stem.upper()] = {"file": rel(p), "copies": _copies(text), "text": text}
screens: list[dict[str, Any]] = []
- for p in _files(legacy, BMS_SUFFIXES):
+ for p in kinds.files(legacy, "bms"):
for m in read_bms(p.read_text(errors="replace"), rel(p)):
copybook = symbolic.get(m.mapset.upper())
users = sorted(name for name, prog in programs.items() if m.mapset.upper() in prog["copies"])
diff --git a/src/reframe/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 text
BMS 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
+
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
Field
Label
Kind
Validation
Line
{fields or '
None found.
'}
+
Actions
Action
Kind
Goes to, as written
Line
{actions or '
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.
+
"""
diff --git a/src/reframe/design/order.py b/src/reframe/design/order.py
new file mode 100644
index 00000000..a913f010
--- /dev/null
+++ b/src/reframe/design/order.py
@@ -0,0 +1,77 @@
+"""Pipeline 4, stage D11: the order of replacement (P4-12, docs/pipeline-4.md section 4 D11). No model.
+
+Each capability has a risk and the list of what it touches (P3-24: money, card data, personal data, security, audit,
+record updates, reporting only). Reframe orders the capabilities for replacement in three waves:
+
+1. **Read-only:** it touches reporting only, or nothing on the list, and its risk is low: reports and inquiry screens.
+2. **Updates:** it updates records or holds card or personal data, and touches no money, security or audit.
+3. **Money, security and audit last:** it touches any of them, or its risk is high (a compliance rule).
+
+Within a wave, lower risk comes first, then final capabilities before drafts, then the specification's own order. A
+capability that shares a data contract or a screen with one already placed follows it at once, so what shares data
+and screens is replaced together. Each place says why, in words.
+
+ design/order.json: {"order": [{"key", "position", "wave", "reason", "with"}], "waves": {...}}
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+FILE = "design/order.json"
+WAVES = {1: "read-only", 2: "updates", 3: "money, security and audit"}
+LAST = {"money", "security", "audit"}
+UPDATES = {"updates_records", "card_data", "personal_data"}
+WORDS = {"money": "money", "card_data": "card data", "personal_data": "personal data", "security": "security", "audit": "audit",
+ "updates_records": "record updates", "reporting_only": "reporting only"}
+RISK = {"low": 0, "": 1, "medium": 1, "high": 2}
+
+
+def wave(s: dict[str, Any]) -> int:
+ touches = set(s.get("touches") or [])
+ if touches & LAST or s.get("risk") == "high":
+ return 3
+ if touches & UPDATES or s.get("risk") == "medium":
+ return 2
+ return 1
+
+
+def shared(a: dict[str, Any], b: dict[str, Any]) -> list[str]:
+ """The data contracts and screens two capabilities share."""
+ books = {c["copybook"] for c in a.get("contracts") or []} & {c["copybook"] for c in b.get("contracts") or []}
+ screens = {x["id"] for x in a.get("screens") or []} & {x["id"] for x in b.get("screens") or []}
+ return sorted(books) + sorted(screens)
+
+
+def why(s: dict[str, Any], w: int) -> str:
+ touches = [WORDS.get(t, t) for t in s.get("touches") or []]
+ what = f"it touches {', '.join(touches)}" if touches else "it touches nothing on the list"
+ risk = f"{s['risk']} risk" if s.get("risk") else "risk not rated"
+ lead = {1: "Read-only, so first", 2: "It changes data, so after the read-only capabilities",
+ 3: "Money, security or audit, so last"}[w]
+ return f"{lead}: {what}; {risk}."
+
+
+def order(specs: list[dict[str, Any]]) -> dict[str, Any]:
+ """The replacement order of the specifications, each place with its wave and reason."""
+ index = {s["key"]: n for n, s in enumerate(specs)}
+ base = sorted(specs, key=lambda s: (wave(s), RISK.get(s.get("risk") or "", 1), s.get("status") != "final", index[s["key"]]))
+ placed: list[dict[str, Any]] = []
+ done: set[str] = set()
+ for s in base:
+ if s["key"] in done:
+ continue
+ queue: list[tuple[dict[str, Any], dict[str, Any] | None]] = [(s, None)]
+ while queue:
+ x, after = queue.pop(0)
+ if x["key"] in done:
+ continue
+ done.add(x["key"])
+ w = wave(x)
+ reason = why(x, w)
+ if after:
+ reason += f" Follows {after['title']}: they share {', '.join(shared(x, after))}."
+ placed.append({"key": x["key"], "title": x["title"], "position": len(placed) + 1, "wave": w, "wave_name": WAVES[w],
+ "reason": reason, "with": after["key"] if after else ""})
+ queue += [(y, x) for y in base if y["key"] not in done and wave(y) == w and shared(x, y)]
+ return {"order": placed, "waves": {WAVES[w]: sum(1 for p in placed if p["wave"] == w) for w in WAVES}}
diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py
index f90ac536..7e9dedb2 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")])
@@ -346,8 +346,14 @@ def design_md(s: dict[str, Any], books: dict[str, Any]) -> str:
"## Testing", "", f"Every acceptance criterion in requirements.md is a test named by its ID ({len(s['acceptance'])} in all)."])
+def order_line(s: dict[str, Any]) -> list[str]:
+ """Where the capability comes in the order of replacement (P4-12), and why; nothing when there is no order."""
+ p = s.get("replacement")
+ return [f"**Order of replacement:** {p['position']} of {p['of']}, {p['wave_name']}. {p['reason']}", ""] if p else []
+
+
def tasks_md(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
- return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + task_lines(s, ts, numbered=True)) + "\n"
+ return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + task_lines(s, ts, numbered=True)) + "\n"
def spec_md(s: dict[str, Any], books: dict[str, Any]) -> str:
@@ -381,7 +387,7 @@ def speckit_plan(s: dict[str, Any], books: dict[str, Any], stack: dict[str, Any]
def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
- out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), "", "Each task names the role that does it; the role files are in .claude/agents/.", ""]
+ out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + ["Each task names the role that does it; the role files are in .claude/agents/.", ""]
for t in ts:
out.append(f"- [ ] {t['id']} [{t['role']}] {md(t['title'])}. Requirements: {', '.join(t['requirements'])}"
+ (f". Rules: {', '.join(t['rules'])}" if t["rules"] else "") + (f". Criteria: {', '.join(t['criteria'])}" if t.get("criteria") else "")
@@ -393,7 +399,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.", ""]
@@ -463,22 +469,28 @@ def traceability_md(specs: list[dict[str, Any]], ts: dict[str, list[dict[str, An
def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: dict[str, Any] | None, journeys: list[dict[str, Any]],
- prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None) -> dict[str, list[dict[str, Any]]]:
+ prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None,
+ replacement: dict[str, Any] | None = None) -> dict[str, list[dict[str, Any]]]:
"""Every form of the package under root. Returns the tasks by capability."""
+ placed = {p["key"]: p for p in (replacement or {}).get("order") or []}
+ specs = [{**s, "replacement": {**placed[s["key"]], "of": len(placed)}} if s["key"] in placed else s for s in specs]
+ by_order = sorted(specs, key=lambda s: (s["replacement"]["position"] if s.get("replacement") else len(specs) + 1))
+ ordered = [f"{s['replacement']['position']}. {s['id']} {md(s['title'])} ({s['replacement']['wave_name']}): {s['replacement']['reason']}"
+ for s in by_order if s.get("replacement")]
datasets = {s["id"]: golden.dataset(s) for s in specs}
ts = {s["id"]: tasks(s, datasets[s["id"]]) for s in specs}
- contracts = "# Data contracts\n\nThe copybooks the capabilities' programs copy, as typed records, read from the legacy source.\n\n" + \
+ contracts = "# Data contracts\n\nThe copybooks, tables or entities the capabilities' code uses, as typed records, read from the legacy source.\n\n" + \
"\n".join(contract_md(c) for c in books.values())
trace = traceability_md(specs, ts)
product = product_md(specs, journeys, project, context.get("personas", ""), context.get("decisions", ""))
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,19 +514,23 @@ 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.", "",
"## Capabilities", "", index, ""])
- files["claude-code/tasks.md"] = "# Tasks\n\nBuild final capabilities first. Each task names its role and the IDs it implements.\n\n" + "\n\n".join(
- f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n"
+ files["claude-code/tasks.md"] = "# Tasks\n\n" + ("Build the capabilities in the order of replacement below, from their risk and what they touch (P4-12). "
+ if ordered else "Build final capabilities first. ") + "Each task names its role and the IDs it implements.\n\n" + "\n\n".join(
+ f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(order_line(s) + task_lines(s, ts[s["id"]])) for s in by_order) + "\n"
for s in specs:
files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books)
- 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([
@@ -524,9 +540,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
"3. Every requirement, rule, acceptance criterion and task keeps its ID, so the build stays traceable to the legacy source (traceability.md).",
"4. The target stack is the engineer's: " + (f"{stack['stack']}." if stack else "not given yet; nothing that depends on it is built until it is."),
"5. Final capabilities (signed off) are built to as written; draft ones are confirmed with the owner first.",
- "6. Order of replacement: final capabilities first; the risk-ranked order (P4-12) will replace this when it exists.",
+ ("6. Order of replacement: the order below, from each capability's risk and what it touches (P4-12): read-only first, then updates, then money, "
+ "security and audit; capabilities that share data or screens are built together. Draft ones are confirmed with the owner first."
+ if ordered else "6. Order of replacement: final capabilities first."),
"7. A business rule is kept exactly; a historical artifact is carried only after asking.", "", "## Roles", ""]
- + [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + ["", "## Technical context", "", handover.technical_context(stack), "",
+ + [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + (["", "## Order of replacement", ""] + ordered if ordered else [])
+ + ["", "## Technical context", "", handover.technical_context(stack), "",
"## House conventions", "", handover.house(context.get("style", "")), "", "## Conventions", ""] + conventions()) + "\n"
for role in ROLES:
files[f"spec-kit/.claude/agents/{role}.md"] = role_md(role)
@@ -653,7 +672,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 +680,11 @@ 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')}"}
+ from reframe.design import order
+ ts = write(root, specs, books, stack, journeys, prototype, project, told, programs, folder.load(order.FILE))
problems = check(root, specs, ts)
made = manifest(specs, ts, stack)
same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root)
diff --git a/src/reframe/design/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..fe9ca402 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,9 +538,11 @@ 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)
+ from reframe.design import order
+ folder.save(order.FILE, order.order(specs)) # the order of replacement (P4-12), from risk and what each touches
value["full"] = specs
value["contracts"] = books
value["round"] = told
@@ -509,7 +558,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"
' : '');
return h;
}
// Pipeline 3: risk per capability and function, and decision tables (docs/pipeline-3.md, section 8.9).
diff --git a/src/reframe/source/kinds.py b/src/reframe/source/kinds.py
new file mode 100644
index 00000000..20d30c45
--- /dev/null
+++ b/src/reframe/source/kinds.py
@@ -0,0 +1,169 @@
+"""What each file in a mainframe snapshot is (MP-01), in one table every reader uses.
+
+The extensions are AWS Transform's, from its user guide's list of mainframe source file types (the page on preparing
+mainframe source artifacts, read 28 November 2026). AWS Transform classifies a file by its extension, and classes a file
+with no extension, or `.txt`, by itself. Reframe does the same: a known extension decides, in any case (`.CBL` is
+`.cbl`), and a file with no extension or `.txt` is classed by its content. Another extension the table does not name
+(`.md`, `.java`, `.j2`) is not mainframe source; the package check (MP-03) says what such a file looks like.
+
+| Kind | AWS Transform's name | Extensions | Content that shows it, when the extension does not |
+|----------------|---------------------------------|------------------------|-----------------------------------------------------|
+| `cobol` | COBOL | .cbl .cob .cobol | an IDENTIFICATION (or ID) DIVISION |
+| `copybook` | Copybooks | .cpy | COBOL data entries (level numbers) and no division |
+| `bms` | BMS | .bms | a DFHMSD macro |
+| `jcl` | JCL | .jcl | a `//name JOB` statement |
+| `proc` | JCL Proc | .prc .proc | a `//name PROC` statement and no JOB |
+| `include` | JCL Includes | .inc | – |
+| `csd` | CICS Definition | .csd | DEFINE TRANSACTION, PROGRAM, MAPSET or FILE |
+| `assembler` | Assembler | .asm | a CSECT, DSECT or START statement |
+| `macro` | Macros | .mac | – |
+| `pli` | PL/I | .pl1 (.pli, Reframe's) | a PROC with OPTIONS(MAIN), or PROC ... END |
+| `pli-copybook` | PL/I copybooks | .pl1_copy | – |
+| `rexx` | REXX | .rex .rexx | a first comment naming REXX |
+| `easytrieve` | Easytrieve | .ezt | – |
+| `natural` | Natural | .nat | – |
+| `dclgen` | Db2 DCLGEN | .dcl | EXEC SQL DECLARE ... TABLE |
+| `ddl` | Db2 definition | .sql .ddl | CREATE TABLE, INDEX, VIEW or TABLESPACE |
+| `ims-stage1` | IMS definition (IMS Stage 1) | .ims | APPLCTN or TRANSACT macros |
+| `dbd` | DBD | .dbd | a DBD macro with NAME= |
+| `psb` | PSB | .psb | a PSBGEN macro, or PCB TYPE= |
+| `mfs` | MFS | .mfs | – |
+| `control-card` | Control Cards | .ctl | – |
+| `ca7` | CA-7 job reports (LJOB) | .ca7 | – |
+| `catalog` | catalog information (LISTCAT) | – | an IDCAMS listing of LISTCAT |
+
+`.pli` is not in AWS Transform's table; Reframe has read it as PL/I since pipeline 3, so it stays. The CICS resource-builder
+YAML some codebases keep their CICS definitions in is read by the design's flow (MP-02); it is not a kind here, since
+AWS Transform's table does not name it.
+"""
+
+from __future__ import annotations
+
+import re
+from functools import lru_cache
+from pathlib import Path
+
+EXTENSIONS: dict[str, str] = {
+ ".cbl": "cobol", ".cob": "cobol", ".cobol": "cobol", ".cpy": "copybook", ".bms": "bms", ".jcl": "jcl", ".prc": "proc",
+ ".proc": "proc", ".inc": "include", ".csd": "csd", ".asm": "assembler", ".mac": "macro", ".pl1": "pli", ".pli": "pli",
+ ".pl1_copy": "pli-copybook", ".rex": "rexx", ".rexx": "rexx", ".ezt": "easytrieve", ".nat": "natural", ".dcl": "dclgen",
+ ".sql": "ddl", ".ddl": "ddl", ".ims": "ims-stage1", ".dbd": "dbd", ".psb": "psb", ".mfs": "mfs", ".ctl": "control-card",
+ ".ca7": "ca7",
+}
+"""Extension -> kind: AWS Transform's table, and `.pli`."""
+
+AWS_NAMES: dict[str, str] = {
+ "cobol": "COBOL", "copybook": "Copybook", "bms": "BMS", "jcl": "JCL", "proc": "JCL Proc", "include": "JCL Include",
+ "csd": "CICS Definition", "assembler": "Assembler", "macro": "Macro", "pli": "PL/I", "pli-copybook": "PL/I copybook",
+ "rexx": "REXX", "easytrieve": "Easytrieve", "natural": "Natural", "dclgen": "Db2 DCLGEN", "ddl": "Db2 definition",
+ "ims-stage1": "IMS definition (Stage 1)", "dbd": "IMS DBD", "psb": "IMS PSB", "mfs": "IMS MFS", "control-card": "Control Card",
+ "ca7": "CA-7 report", "catalog": "catalog listing (LISTCAT)",
+}
+
+AWS_EXTENSIONS = frozenset(EXTENSIONS) - {".pli"}
+"""The extensions AWS Transform's table names."""
+
+BY_CONTENT = frozenset({"", ".txt"})
+HEAD = 65536 # bytes read to class a file by its content
+
+
+def _code(line: str) -> str:
+ """A fixed-format line's code: columns 8 to 72 when the sequence area is there, with comment lines dropped."""
+ if len(line) > 6 and line[6] in "*/" and (line[:6].strip() == "" or line[:6].isdigit()):
+ return ""
+ return line
+
+
+def content_kind(text: str) -> str | None:
+ """The kind a file's content shows, or None. Read from the first lines that are not comments."""
+ upper = text.upper()
+ lines = [line for line in upper.splitlines() if line.strip()]
+ code = "\n".join(_code(line) for line in lines)
+ first = next((line for line in lines if not line.lstrip().startswith(("*", "//*"))), "")
+ if "IDCAMS" in upper and "LISTCAT" in upper:
+ return "catalog"
+ if re.search(r"^//\S*\s+JOB\b", code, re.M):
+ return "jcl"
+ if re.search(r"^//\S*\s+PROC\b", code, re.M):
+ return "proc"
+ if re.search(r"\b(IDENTIFICATION|ID)\s+DIVISION\b", code):
+ return "cobol"
+ if re.search(r"^\S*\s+DFHMSD\b", code, re.M):
+ return "bms"
+ if re.search(r"^\s*DEFINE\s+(TRANSACTION|PROGRAM|MAPSET|FILE)\s*\(", code, re.M):
+ return "csd"
+ if re.search(r"^\S*\s+DBD\s+.*\bNAME=", code, re.M):
+ return "dbd"
+ if re.search(r"^\S*\s+PSBGEN\b", code, re.M) or re.search(r"^\S*\s+PCB\s+TYPE=", code, re.M):
+ return "psb"
+ if re.search(r"^\S*\s+(APPLCTN|TRANSACT)\b", code, re.M):
+ return "ims-stage1"
+ if first.lstrip().startswith("/*") and "REXX" in first:
+ return "rexx"
+ if re.search(r"\bEXEC\s+SQL\s+DECLARE\s+\S+\s+TABLE\b", code):
+ return "dclgen"
+ if re.search(r"^\s*CREATE\s+(TABLE|INDEX|UNIQUE\s+INDEX|VIEW|TABLESPACE)\b", code, re.M):
+ return "ddl"
+ if re.search(r"\bPROC\s+OPTIONS\s*\(\s*MAIN\b", code) or (re.search(r":\s*PROC(EDURE)?\b", code) and re.search(r"\bEND\b", code)):
+ return "pli"
+ if re.search(r"^\S*\s+(CSECT|DSECT|START)\b", code, re.M):
+ return "assembler"
+ entries = [line for line in code.splitlines() if line.strip()]
+ data = sum(1 for line in entries if re.match(r"^.{0,11}\b(0?[1-9]|[1-4][0-9]|66|77|88)\s+[A-Z0-9][A-Z0-9-]*\b", line))
+ if entries and data >= max(1, len(entries) // 2) and re.search(r"\b(PIC|PICTURE|REDEFINES|OCCURS|VALUE)\b", code):
+ return "copybook"
+ return None
+
+
+def read_head(path: Path) -> bytes:
+ with path.open("rb") as handle:
+ return handle.read(HEAD)
+
+
+def classify(name: str, head: bytes) -> str | None:
+ """The kind of a file from its name and its first bytes: its extension when the table names it, its content when it
+ has no extension or `.txt`, and nothing for another extension or a file that is not text."""
+ suffix = Path(name).suffix.lower()
+ if suffix not in BY_CONTENT:
+ return EXTENSIONS.get(suffix)
+ if b"\x00" in head:
+ return None
+ return content_kind(head.decode("utf-8", errors="replace"))
+
+
+@lru_cache(maxsize=65536)
+def _kind_cached(path: str, size: int, mtime: float) -> str | None:
+ p = Path(path)
+ if p.suffix.lower() not in BY_CONTENT:
+ return EXTENSIONS.get(p.suffix.lower())
+ try:
+ return classify(p.name, read_head(p))
+ except OSError:
+ return None
+
+
+def kind_of(path: Path) -> str | None:
+ """The kind of one file: its extension when the table names it, its content when it has no extension or `.txt`."""
+ try:
+ stat = path.stat()
+ except OSError:
+ return None
+ return _kind_cached(str(path), stat.st_size, stat.st_mtime)
+
+
+def files(root: Path, *kinds: str) -> list[Path]:
+ """Every file under root of one of the kinds, in name order."""
+ wanted = set(kinds)
+ return sorted(p for p in root.rglob("*") if p.is_file() and kind_of(p) in wanted)
+
+
+def is_source(path: Path) -> bool:
+ """A file Reframe reads as mainframe source: any kind but the system extracts (catalog listings and CA-7 reports)."""
+ return kind_of(path) not in (None, "catalog", "ca7")
+
+
+def copybooks(root: Path) -> list[Path]:
+ """Every COBOL copybook, by its extension or its content, and as before the files with no extension in a folder whose
+ name starts with `cpy` that show nothing else (CardDemo keeps some copybooks that way)."""
+ return sorted(p for p in root.rglob("*") if p.is_file() and (
+ kind_of(p) == "copybook" or (p.suffix == "" and kind_of(p) is None and p.parent.name.lower().startswith("cpy"))))
diff --git a/src/reframe/source/package_check.py b/src/reframe/source/package_check.py
new file mode 100644
index 00000000..0fb45167
--- /dev/null
+++ b/src/reframe/source/package_check.py
@@ -0,0 +1,156 @@
+"""The package check (MP-03): what AWS Transform will make of a snapshot, before anything is uploaded.
+
+It reads the snapshot's archive, changes nothing, and writes `package-check.json` in the run folder:
+
+- `kinds`: every file's kind in Reframe's table (reframe.source.kinds), by extension or, with none, by content;
+- `unnamed`: files whose extension AWS Transform's table does not name, by extension, and those whose content looks like
+ mainframe source all the same (for example JCL kept as a template, `.j2`);
+- `disagree`: files whose content is not what their extension says, with what AWS Transform takes them as (IMS DBD and
+ PSB macros kept as `.asm` are taken as Assembler);
+- `binary`: files that are not text. AWS Transform reads source as text; SMF data belongs in its own folder;
+- `encodings`: the encodings of the source files. AWS Transform asks for one encoding across the files it documents;
+- `extracts`: the system extracts present: a catalog listing (LISTCAT), CICS definitions (a CSD extract, or IBM's
+ resource-builder YAML, which Reframe reads and AWS Transform's table does not name), IMS Stage 1 and CA-7 reports;
+- `notes`: the findings in words, shown by `reframe status` and on the reports.
+"""
+
+from __future__ import annotations
+
+import zipfile
+from collections import Counter
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from reframe.source import kinds
+
+FILE = "package-check.json"
+SAMPLE = 50 # files listed per finding; the counts are whole
+SAME = [{"jcl", "proc", "include"}, {"copybook", "dclgen"}, {"assembler", "macro"}, {"pli", "pli-copybook"}]
+EXTRACTS = {"catalog": "catalog listing (LISTCAT)", "cics": "CICS definitions (CSD extract or resource-builder YAML)",
+ "ims-stage1": "IMS Stage 1 definitions", "ca7": "CA-7 job reports"}
+EBCDIC_TEXT = set(range(0x81, 0x8A)) | set(range(0x91, 0x9A)) | set(range(0xA2, 0xAA)) | set(range(0xC1, 0xCA)) | \
+ set(range(0xD1, 0xDA)) | set(range(0xE2, 0xEA)) | set(range(0xF0, 0xFA)) | {0x40, 0x4B, 0x5C, 0x61, 0x6B, 0x7D, 0x7E}
+
+
+def encoding(head: bytes) -> str:
+ """`ascii`, `utf-8`, `ebcdic`, `other` (text in another single-byte encoding) or `binary`."""
+ if not head:
+ return "ascii"
+ if b"\x00" in head:
+ return "binary"
+ try:
+ head.decode("utf-8")
+ except UnicodeDecodeError as error:
+ if error.start < len(head) - 3: # not merely a character cut off at the end of what was read
+ if sum(b in EBCDIC_TEXT for b in head) / len(head) > 0.8 and sum(0x61 <= b <= 0x7A for b in head) / len(head) < 0.05:
+ return "ebcdic"
+ controls = sum(b < 0x09 or 0x0E <= b < 0x20 for b in head)
+ return "binary" if controls / len(head) > 0.1 else "other"
+ return "ascii" if max(head) < 0x80 else "utf-8"
+
+
+def _same(a: str, b: str) -> bool:
+ return a == b or any(a in group and b in group for group in SAME)
+
+
+def check_archive(archive: Path) -> dict[str, Any]:
+ with zipfile.ZipFile(archive) as z:
+ members = [(m.filename, z.open(m).read(kinds.HEAD)) for m in z.infolist() if not m.is_dir()]
+ return check_members(members)
+
+
+def check_members(members: list[tuple[str, bytes]]) -> dict[str, Any]:
+ """The check of a list of (path in the snapshot, first bytes of the file)."""
+ kinds_found: Counter[str] = Counter()
+ unnamed: Counter[str] = Counter()
+ looks: list[dict[str, str]] = []
+ disagree: list[dict[str, str]] = []
+ binary: list[str] = []
+ encodings: Counter[str] = Counter()
+ extracts: dict[str, list[str]] = {key: [] for key in EXTRACTS}
+ for name, head in sorted(members):
+ suffix = PurePosixPath(name).suffix.lower()
+ enc = encoding(head)
+ kind = kinds.classify(name, head)
+ text = head.decode("utf-8", errors="replace") if enc != "binary" else ""
+ shown = kinds.content_kind(text) if text else None
+ if enc == "binary":
+ binary.append(name)
+ if kind:
+ kinds_found[kind] += 1
+ encodings[enc] += 1
+ if suffix not in kinds.BY_CONTENT and suffix not in kinds.AWS_EXTENSIONS:
+ unnamed[suffix] += 1
+ if shown:
+ looks.append({"file": name, "looks_like": kinds.AWS_NAMES[shown]})
+ elif suffix in kinds.AWS_EXTENSIONS and kind and shown and not _same(kind, shown):
+ disagree.append({"file": name, "extension": kinds.AWS_NAMES[kind], "content": kinds.AWS_NAMES[shown],
+ "aws_takes_it_as": kinds.AWS_NAMES[kind]})
+ if kind in ("catalog", "ims-stage1", "ca7"):
+ extracts[kind].append(name)
+ if kind == "csd" or (suffix in (".yaml", ".yml") and "resourceDefinitions" in text):
+ extracts["cics"].append(name)
+ found: dict[str, Any] = {
+ "files": len(members), "kinds": dict(kinds_found.most_common()),
+ "unnamed": {"count": sum(unnamed.values()), "extensions": dict(unnamed.most_common()), "looks_like_source": looks[:SAMPLE],
+ "looks_like_source_count": len(looks)},
+ "disagree": disagree[:SAMPLE], "disagree_count": len(disagree),
+ "binary": binary[:SAMPLE], "binary_count": len(binary),
+ "encodings": dict(encodings.most_common()),
+ "extracts": {key: files[:SAMPLE] for key, files in extracts.items()},
+ }
+ found["notes"] = notes(found)
+ return found
+
+
+def notes(found: dict[str, Any]) -> list[str]:
+ said = []
+ source = sum(found["kinds"].values())
+ said.append(f"{found['files']} files, {source} of them mainframe source by AWS Transform's table of extensions or by their content.")
+ u = found["unnamed"]
+ if u["count"]:
+ top = ", ".join(f"{ext or '(none)'} {n}" for ext, n in list(u["extensions"].items())[:6])
+ said.append(f"{u['count']} files have an extension AWS Transform's table does not name ({top}); it may leave them out."
+ + (f" {u['looks_like_source_count']} of them look like mainframe source all the same, for example "
+ f"{u['looks_like_source'][0]['file']} ({u['looks_like_source'][0]['looks_like']})." if u["looks_like_source_count"] else ""))
+ for ext, n in u["extensions"].items():
+ if ext in kinds.EXTENSIONS: # Reframe reads it; AWS Transform's table names another extension for the same kind
+ kind = kinds.EXTENSIONS[ext]
+ named = sorted(e for e, k in kinds.EXTENSIONS.items() if k == kind and e in kinds.AWS_EXTENSIONS)
+ said.append(f"{n} {ext} files are {kinds.AWS_NAMES[kind]}: Reframe reads them, but AWS Transform's table names "
+ f"{' and '.join(named)}, so it may leave them out.")
+ if found["disagree_count"]:
+ first = found["disagree"][0]
+ said.append(f"{found['disagree_count']} files hold something other than their extension says, for example {first['file']}: "
+ f"{first['content']}, which AWS Transform takes as {first['aws_takes_it_as']}.")
+ if found["binary_count"]:
+ said.append(f"{found['binary_count']} files are not text. AWS Transform reads source as text; SMF data goes in its own "
+ "folder, not with the source.")
+ text = {k: v for k, v in found["encodings"].items() if k != "binary"}
+ families = {"utf-8" if k in ("ascii", "utf-8") else k for k in text}
+ if len(families) > 1:
+ said.append("The source files are not in one encoding (" + ", ".join(f"{k} {v}" for k, v in text.items())
+ + "). AWS Transform asks for one; otherwise its documentation may have empty sections.")
+ present = [EXTRACTS[k] for k, v in found["extracts"].items() if v]
+ missing = [EXTRACTS[k] for k, v in found["extracts"].items() if not v]
+ if present:
+ said.append("System extracts present: " + ", ".join(present) + ".")
+ if missing:
+ said.append("Not present: " + ", ".join(missing) + ". They come from the running system; the guide says how.")
+ return said
+
+
+def summary(found: dict[str, Any] | None) -> str:
+ """One line for `reframe status` and the reports."""
+ if not found:
+ return ""
+ parts = [f"{found['files']} files, {sum(found['kinds'].values())} mainframe source"]
+ if found["unnamed"]["count"]:
+ parts.append(f"{found['unnamed']['count']} with extensions AWS Transform does not name")
+ if found["disagree_count"]:
+ parts.append(f"{found['disagree_count']} whose content and extension disagree")
+ if found["binary_count"]:
+ parts.append(f"{found['binary_count']} not text")
+ families = {"utf-8" if k in ("ascii", "utf-8") else k for k in found["encodings"] if k != "binary"}
+ parts.append("one encoding" if len(families) <= 1 else "mixed encodings")
+ return "; ".join(parts)
diff --git a/src/reframe/source/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 1dd835ed..90b1a1fb 100644
--- a/src/reframe/source/snapshot.py
+++ b/src/reframe/source/snapshot.py
@@ -8,7 +8,9 @@
| a GitHub (or other Git) URL | cloned into the run folder at --ref, then git archive of that commit |
Every archive is checked the same way before it is used: it opens, has no absolute or ".." paths and no
-links, and unpacks to at most 2 GB.
+links, and unpacks to at most 2 GB. Then the package check (reframe.source.package_check, MP-03) records what AWS
+Transform will make of it in package-check.json, before anything is uploaded, and the stack profile
+(reframe.source.profile, L1-01) what the codebase is, in stack-profile.json.
"""
from __future__ import annotations
@@ -139,6 +141,15 @@ def take(folder: RunFolder, source: str, ref: str | None, runner: Runner = run_s
shutil.copyfile(Path(source).expanduser(), archive)
archive.chmod(0o600)
files = check_archive(archive)
+ from reframe.source import package_check
+ checked = package_check.check_archive(archive) # what AWS Transform will make of it (MP-03); the archive is not changed
+ folder.save(package_check.FILE, checked)
+ folder.event("package_checked", files=checked["files"], unnamed=checked["unnamed"]["count"], disagree=checked["disagree_count"],
+ binary=checked["binary_count"], encodings=",".join(checked["encodings"]))
+ 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_flow.py b/tests/design/test_flow.py
index d06491fa..0c773961 100644
--- a/tests/design/test_flow.py
+++ b/tests/design/test_flow.py
@@ -148,5 +148,65 @@ def test_branch_ends_at_the_closing_when(self):
self.assertIn("SPACES", " ".join(program.lines[first - 1:last]))
+RESOURCE_BUILDER = """# yaml-language-server: $schema=./resource-schema.json
+
+resourceDefinitions:
+ - mapset:
+ name: SIGN00
+ group: DEMOGRP
+ - transaction:
+ name: SG00
+ group: DEMOGRP
+ description: Sign on
+ program: SIGN00C
+ - program:
+ name: SIGN00C
+ group: DEMOGRP
+ - transaction:
+ name: "C$#@"
+ group: DEMOGRP
+ program: MENU00C
+"""
+
+
+class CicsDefinitionsTest(unittest.TestCase):
+ """MP-02: transactions from DFHCSDUP's DEFINE statements, national characters included, and from IBM's CICS
+ resource-builder YAML, each citing its line."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+
+ def write(self, name, text):
+ (self.root / name).parent.mkdir(parents=True, exist_ok=True)
+ (self.root / name).write_text(text)
+
+ def test_national_characters_in_the_csd(self):
+ self.write("cics/DEMO.csd", " DEFINE TRANSACTION(C$01) GROUP(DEMO)\n PROGRAM(#MENU@) TWASIZE(0)\n"
+ " DEFINE TRANSACTION( MN00 ) GROUP(DEMO) PROGRAM( MENU00C )\n")
+ self.assertEqual([(t["transaction"], t["program"], t["lines"]) for t in flow.transactions(self.root)],
+ [("C$01", "#MENU@", ["cics/DEMO.csd:1"]), ("MN00", "MENU00C", ["cics/DEMO.csd:3"])])
+
+ def test_resource_builder_yaml(self):
+ self.write(".setup/zconfig/demo-definitions.yaml", RESOURCE_BUILDER)
+ self.write(".setup/zconfig/region.yaml", "region:\n transaction: XX00\n") # other YAML gives nothing
+ self.write("broken.yaml", "resourceDefinitions: [unclosed\n")
+ found = flow.transactions(self.root)
+ self.assertEqual([(t["transaction"], t["program"], t["lines"]) for t in found],
+ [("SG00", "SIGN00C", [".setup/zconfig/demo-definitions.yaml:7"]), ("C$#@", "MENU00C", [".setup/zconfig/demo-definitions.yaml:15"])])
+ lines = (self.root / ".setup/zconfig/demo-definitions.yaml").read_text().splitlines()
+ self.assertEqual(lines[6].strip(), "- transaction:")
+
+ def test_yaml_transactions_reach_their_programs_in_the_flow(self):
+ self.write("cbl/SIGN00C.cbl", SIGNON)
+ self.write("cbl/MENU00C.cbl", MENU)
+ self.write("cpy/MENU02Y.cpy", MENU_TABLE)
+ self.write("defs.yml", RESOURCE_BUILDER)
+ found = flow.flow(self.root, inventory.inventory(self.root))
+ self.assertEqual({(x["from"], x["to"]) for x in found["links"] if x["kind"] == "transaction"}, {("SG00", "SIGN00C"), ("C$#@", "MENU00C")})
+ self.assertEqual(flow.check(found, self.root), []) # every cited line exists
+
+
if __name__ == "__main__":
unittest.main()
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_order.py b/tests/design/test_order.py
new file mode 100644
index 00000000..3f45ce2a
--- /dev/null
+++ b/tests/design/test_order.py
@@ -0,0 +1,77 @@
+"""P4-12: risk and replacement order (docs/pipeline-4.md, section 4 D11). Capabilities are ordered for replacement from
+their risk and what they touch, read-only first and money, security and audit last, shared data and screens kept
+together; the order and its reasons are on the design page and in the package's constitution and tasks."""
+import unittest
+from pathlib import Path
+
+from reframe.design import order, pipeline
+from tests.design.test_pipeline import RoundsTest
+
+
+def cap(key, risk="", touches=(), books=(), screens=(), status="draft"):
+ return {"key": key, "title": key.title(), "risk": risk, "touches": list(touches), "status": status,
+ "contracts": [{"copybook": b} for b in books], "screens": [{"id": s} for s in screens]}
+
+
+class OrderTest(unittest.TestCase):
+ def test_read_only_first_then_updates_then_money_security_and_audit(self):
+ found = order.order([cap("pay", "high", ["money"]), cap("report", "low", ["reporting_only"]), cap("update", "medium", ["updates_records"]),
+ cap("signon", "high", ["security"]), cap("inquiry", "low")])
+ self.assertEqual([(p["key"], p["wave_name"]) for p in found["order"]],
+ [("report", "read-only"), ("inquiry", "read-only"), ("update", "updates"),
+ ("pay", "money, security and audit"), ("signon", "money, security and audit")])
+ self.assertEqual(found["waves"], {"read-only": 2, "updates": 1, "money, security and audit": 2})
+ first = found["order"][0]["reason"]
+ self.assertEqual(first, "Read-only, so first: it touches reporting only; low risk.")
+ self.assertIn("Money, security or audit, so last: it touches money; high risk.", found["order"][3]["reason"])
+
+ def test_within_a_wave_lower_risk_then_final_first(self):
+ found = order.order([cap("b", "medium", ["card_data"]), cap("a", "low", ["personal_data"], status="draft"),
+ cap("c", "low", ["personal_data"], status="final")])
+ self.assertEqual([p["key"] for p in found["order"]], ["c", "a", "b"])
+
+ def test_shared_data_and_screens_follow_at_once(self):
+ found = order.order([cap("view", "low", books=["ACCT"]), cap("list", "low", screens=["S-LIST"]), cap("detail", "low", books=["ACCT"]),
+ cap("other", "low", screens=["S-LIST"])])
+ self.assertEqual([p["key"] for p in found["order"]], ["view", "detail", "list", "other"])
+ detail = next(p for p in found["order"] if p["key"] == "detail")
+ self.assertEqual(detail["with"], "view")
+ self.assertTrue(detail["reason"].endswith("Follows View: they share ACCT."))
+
+ def test_sharing_never_pulls_a_capability_into_an_earlier_wave(self):
+ found = order.order([cap("view", "low", books=["ACCT"]), cap("pay", "high", ["money"], books=["ACCT"]), cap("report", "low")])
+ self.assertEqual([p["key"] for p in found["order"]], ["view", "report", "pay"])
+
+
+class InThePackageTest(RoundsTest):
+ """On the design fixture (sign-on, high risk for security; the account view, not rated): the page and the package."""
+
+ def test_the_order_on_the_page_and_in_the_package(self):
+ value = pipeline.run(self.folder, self.claude)
+ placed = self.folder.load(order.FILE)["order"]
+ self.assertEqual([p["key"] for p in placed], ["rec/Accounts/View#1", "rec/Access/SignOn#1"]) # security last
+ page = self.folder.path("outputs/design/index.html").read_text()
+ self.assertIn('