From legacy source to reviewed requirements, business rules and a design to build from.
- Tested end to end on mainframe COBOL and CICS. On other languages, Claude's assessment and the reconciliation should work, untested.
+ Tested end to end on mainframe COBOL and CICS. Java, .NET and PHP are tested offline, with live runs to come.
@@ -43,10 +43,17 @@
Reframe reads a legacy codebase and tells you, in plain words a business can review, what it does. It assesses the code with Claude's [code-modernization plugin](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-modernization), and with AWS Transform as well if you have it, then checks every business rule against the source code itself. From that it designs the modern application, down to a package an AI coding tool can build from.
-| Codebase | What runs | Tested |
-|---|---|---|
-| **Mainframe:** COBOL, JCL, CICS, BMS | Everything: Claude's assessment and AWS Transform's, the reconciliation against the code, the design and the package | **Yes**, end to end on AWS's CardDemo |
-| **Other languages:** Java, .NET, PHP, Python, C and more | With Claude only, since AWS Transform writes requirements only for the mainframe. The assessment and the reconciliation should work: Claude's plugin reads any language. The design reads screens, flows and data definitions from mainframe sources only, so it stops on other codebases for now | **No.** Full support is planned ([the 1.1 specification](docs/any-legacy.md)) |
+Reframe works out what the codebase is first, its *stack profile*, and picks its tools and readers from it:
+
+| Family | Tools | How the design reads screens, flow and data | Proven |
+|---|---|---|---|
+| **Mainframe:** COBOL, PL/I, JCL, CICS, BMS, IMS | Claude's assessment and AWS Transform's, reconciled | Exact readers with no model: BMS maps, CICS transfers and definitions (CSD or resource-builder YAML), copybooks | **End to end** on AWS's CardDemo |
+| **Java:** Java, JSP, JSF, Groovy, Kotlin | Claude only: AWS Transform writes requirements only for the mainframe | The general reader: views, fields and actions by a checked Claude step; links from routes and patterns; SQL DDL with no model, entities by a checked step | Offline, on small fixtures |
+| **.NET:** C#, VB.NET, ASP.NET, Razor | Claude only | The general reader, with the MVC conventions | Offline, on small fixtures |
+| **Web scripts:** PHP, Perl, Ruby, Python, classic ASP | Claude only | The general reader | Offline, on small fixtures |
+| **Front end, native, 4GL, mixed** | Claude only | The general reader | **Not yet:** they run, unproven |
+
+A codebase with no screens (a batch system, a service or a library) gets its specifications, golden datasets, package and backlog without journeys, screens or a prototype. Live runs on two codebases beyond the mainframe come next ([the 1.1 specification](docs/any-legacy.md)).
It is for modernization teams, architects and the business people who have to say "yes, that is what the system does" before anything is rebuilt.
@@ -221,12 +228,12 @@ The figures are from live runs and are recorded in [docs/acceptance.md](docs/acc
| [How to run Reframe](docs/how-to-run.md) | One page from install to handover |
| [The guide](docs/guide.md) | Every step in detail: the guided run, Claude only, results, reviews, the reconciliation, the design, sharing and teardown |
| [Commands](docs/cli.md) | Every command, option and example |
-| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md) |
+| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md), [any legacy codebase](docs/any-legacy.md) |
| [The plan](docs/plan.md) | Every story, with what done means and the results |
## Roadmap
-- **Beyond the mainframe (1.1):** any legacy codebase Claude's plugin reads (Java, .NET, PHP and more), with Claude only, and screens, flows and data contracts read for each stack ([the specification](docs/any-legacy.md)).
+- **Beyond the mainframe (1.1):** built and tested offline: the stack profile, Claude-only runs by family, the reconciliation in the stack's words, and screens, flows, data contracts and "runs as" read for each stack. Live acceptance on two codebases comes next ([the specification](docs/any-legacy.md)).
- **Proof at scale:** a codebase several times CardDemo's size, and a mainframe expert's own check of the audit.
- **Later:** a replacement order from the specifications, real legacy outputs under GnuCOBOL, and Claude on Amazon Bedrock, live ([docs/plan.md](docs/plan.md)).
diff --git a/docs/cli.md b/docs/cli.md
index bdde6f59..d1b7ecc5 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -94,11 +94,11 @@ Every command acts on your latest run; add `--run ` for another one. The
### `reframe run`
-Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown.
+Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown.
| Option | What it does |
|---|---|
-| `--source ` | the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up |
+| `--source ` | the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up |
| `--profile ` | the AWS CLI profile to sign in with (default: the one saved by the guided setup) |
| `--ref ` | for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD) |
| `--mode autonomous\|interactive` | autonomous: Reframe answers AWS and records why; interactive: answer each question with reframe answer |
@@ -108,6 +108,7 @@ Assess mainframe source with AWS Transform and Claude, or with Claude only (--to
| `--terraform ` | the Terraform binary to use (default: REFRAME_TERRAFORM, then the one Reframe installed, then terraform on PATH) |
| `--foreground` | run in this terminal instead of a background worker |
| `--tools both\|claude\|aws` | both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: AWS Transform only (reframe claude adds Claude later) |
+| `--legacy mainframe\|java\|dotnet\|web-script\|front-end\|native\|4gl\|mixed` | the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, section 4); AWS Transform is offered only for mainframe |
| `--max-agents ` | the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo) |
| `--auth subscription\|api-key\|bedrock` | how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock (with --tools claude, --profile and --region are used for Bedrock only) |
diff --git a/docs/guide.md b/docs/guide.md
index 4c06d2cd..08d63a46 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -5,6 +5,7 @@ Everything about running Reframe, step by step. Start with [How to run Reframe](
- [The home screen](#the-home-screen)
- [Run an assessment: the guided way](#run-an-assessment-the-guided-way)
- [Bringing source from a mainframe](#bringing-source-from-a-mainframe)
+- [What Reframe reads for each stack](#what-reframe-reads-for-each-stack)
- [Claude only, with no AWS](#claude-only-with-no-aws)
- [If a run stops](#if-a-run-stops)
- [Results](#results)
@@ -168,6 +169,38 @@ A Git repository of the application, like CardDemo's, is the easiest source. Cod
Where the check finds something, fix the package and start a new run, or go ahead knowing what AWS Transform will leave out.
+## What Reframe reads for each stack
+
+After the snapshot, Reframe works out what the codebase is, with no model, and records it in `stack-profile.json` in the run folder:
+- its languages, by file and by line;
+- its family: the one that carries more than half the lines;
+- what it has, with the files that show it: screens, routes, jobs and data.
+
+`reframe status` shows it, and so do the reviews. `reframe run --legacy ` overrides the family. For a local source, the guided run shows the profile before it starts, and asks only when no family carries most of the code.
+
+### Mainframe
+
+As in the rest of this guide:
+- Both assessments, AWS Transform's and Claude's, reconciled.
+- The exact readers, with no model: BMS maps for the screens, CICS transfers and definitions for the flow (a CSD extract or IBM's resource-builder YAML), and copybooks for the data contracts.
+- The prompts speak of COBOL, PERFORM, CALL and copybooks.
+
+### Java, .NET, web scripts and the rest
+
+AWS Transform writes requirements only for mainframe code. So these runs are Claude only (`reframe run --tools claude`): Reframe refuses `--tools both` or `aws` before it creates anything, and the guided run does not offer AWS Transform.
+
+- **Programs** are source files, named by their path, so two `OrderService.java` files in different folders stay apart.
+- **The reconciliation** speaks of the stack's languages, and of following a call, an include, an import or an inherited method. Every cited line is still checked against the snapshot.
+- **Screens:** the general reader reads the views, pages and forms the profile found. A Claude step lists each screen's fields and actions; Reframe checks every line it cites, asks again once with the reasons, and otherwise keeps the screen with no fields.
+- **Flow:** links are read from patterns with no model: an href, a form's action, a redirect, Spring and JAX-RS route annotations, Stripes' `@UrlBinding`, the ASP.NET MVC conventions, and a script page's own path. A checked Claude step settles the rest; what fails twice stays open, on the flow page.
+- **Data contracts:** `CREATE TABLE` in SQL DDL, read with no model. Entity classes (JPA, Entity Framework) by a checked Claude step.
+- **Runs as:** online when the rules are in code behind a screen; a scheduled job when a job definition (cron, Quartz, Spring Batch, `@Scheduled`, Windows tasks) runs them; a service when only routes reach them; a library otherwise.
+- **Legacy screens** are shown as their fields and actions, citing the view's lines. The old page is not drawn.
+
+### A codebase with no screens
+
+A batch system, a service or a library gets its final specifications, golden datasets, package and backlog. The journeys, modern screens and prototype are left out, and the design page says why.
+
## Claude only, with no AWS
No AWS account, or no AWS Transform? Run Reframe with Claude only ([release 1.0](release-1.md), section 2). It needs Git, [Claude Code](https://docs.anthropic.com/en/docs/claude-code) signed in, and the code-modernization plugin, which Reframe fetches itself. Claude signs in with your Claude subscription (the default), an Anthropic API key (`--auth api-key`, with `ANTHROPIC_API_KEY` set), or Amazon Bedrock (`--auth bedrock --profile --region `, the profile used for Bedrock only, or `AWS_BEARER_TOKEN_BEDROCK`).
diff --git a/docs/images/cli-help.svg b/docs/images/cli-help.svg
index b82185c2..ad53e324 100644
--- a/docs/images/cli-help.svg
+++ b/docs/images/cli-help.svg
@@ -19,325 +19,325 @@
font-weight: 700;
}
- .terminal-4233349274-matrix {
+ .terminal-612813835-matrix {
font-family: Fira Code, monospace;
font-size: 20px;
line-height: 24.4px;
font-variant-east-asian: full-width;
}
- .terminal-4233349274-title {
+ .terminal-612813835-title {
font-size: 18px;
font-weight: bold;
font-family: arial;
}
- .terminal-4233349274-r1 { fill: #68a0b3 }
-.terminal-4233349274-r2 { fill: #c5c8c6 }
-.terminal-4233349274-r3 { fill: #398280;font-weight: bold }
-.terminal-4233349274-r4 { fill: #c5c8c6;font-weight: bold }
-.terminal-4233349274-r5 { fill: #325e5d;font-weight: bold }
-.terminal-4233349274-r6 { fill: #398280 }
-.terminal-4233349274-r7 { fill: #868887 }
+ .terminal-612813835-r1 { fill: #68a0b3 }
+.terminal-612813835-r2 { fill: #c5c8c6 }
+.terminal-612813835-r3 { fill: #398280;font-weight: bold }
+.terminal-612813835-r4 { fill: #c5c8c6;font-weight: bold }
+.terminal-612813835-r5 { fill: #325e5d;font-weight: bold }
+.terminal-612813835-r6 { fill: #398280 }
+.terminal-612813835-r7 { fill: #868887 }
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
- reframe --help
+ reframe --help
-
+
-
- ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
-││
-│REFRAME│
-│From mainframe source to reviewed requirements, business rules and a design to build from│
-│Prerequisites → Sign in → Source → AWS Transform and Claude → Review → Reconcile → Design →│
-│Share│
-││
-╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯
-
-Commands
-Command What it does
-──────────────────────────────────────────────────────────────────────────────────────────────────────────────
-reframe run Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools
-claude, no AWS): with no options, a guided run that checks and sets up everything first;
-the AWS resources stay until reframe teardown
-reframe setup Check and set up the prerequisites and the AWS sign-in, without starting a run
-reframe status The run's stage, the job's plan steps, any waiting question and the next step
-reframe events The run's event log
-reframe answer Show AWS's waiting question, or answer it
-reframe resume Continue a run that stopped; nothing with a receipt is repeated
-reframe report Build the HTML report from the run's downloads again
-reframe claude The Claude assessment: assess the same snapshot with Claude's code-modernization plugin,
-show it in the same business review, load its graph into the run's Neptune cluster, and
-compare it with AWS Transform's results
-reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude
-only, every rule) against the source code, with evidence Reframe checks, then write
-recommended requirements, one SME list and the reconciliation page; needs the run's
-assessments done, and no AWS resources
-reframe review Read the review downloads in a folder and show each reviewer's coverage, sign-offs and
-where reviewers disagree; runs nothing, and the next reframe reconcile --context with
-the same folder combines them
-reframe export Write a run's reconciled results as one Excel workbook: domains, functions,
-capabilities, requirements, business rules, decision tables, open questions and the SME
-list, with the reviewers' marks; runs nothing
-reframe design The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,
-final specifications and the AI-DLC package, from the reconciled results; a round redoes
-only what new context touches
-reframe compare Build the page comparing AWS Transform's and Claude's results again
-reframe publish Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder
-others can open, upload the run's source, results and reports to your account's private
-bucket, or publish the copy to a GitHub Pages site
-reframe reports The reports published to your AWS account: list them, open one with your AWS sign-in, or
-remove the bucket
-reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them
-
-Examples
-reframe the home screen: your runs, the next step and a menu
-reframe run a guided run: checks the prerequisites, the AWS
-sign-in and the source, then starts
-reframe run --source <folder | file.zip | github-url>start straight away, with no questions
-reframe run --tools claude --source <source> Claude only: no AWS account, nothing to tear down
-reframe status where the latest run is, and what to do next
-reframe answer AWS's waiting question, in interactive mode
-reframe report --open open the business review in the browser
-reframe claude the Claude assessment: the same snapshot, assessed
-with Claude as well
-reframe compare --open open the page comparing AWS Transform and Claude
-reframe export --to xlsx the reconciled requirements and business rules as an
-Excel workbook
-reframe design --open the design: screens, journeys, the prototype, final
-specifications and the AI-DLC package
-reframe publish --to aws upload the run's source, results and cleaned reports
-to your account's private bucket
-reframe reports list the published reports; reframe reports open
-<project> opens the latest
-reframe teardown remove the AWS resources the run created
-
-Options
---version show program's version number and exit
--h, --help this help
-reframe <command> --help shows a command's options.
+
+ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
+││
+│REFRAME│
+│From legacy source to reviewed requirements, business rules and a design to build from│
+│Prerequisites → Sign in → Source → AWS Transform and Claude → Review → Reconcile → Design →│
+│Share│
+││
+╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯
+
+Commands
+Command What it does
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────
+reframe run Assess legacy source with Claude, and mainframe source with AWS Transform beside it
+(--tools claude: Claude only, no AWS): with no options, a guided run that checks and
+sets up everything first; the AWS resources stay until reframe teardown
+reframe setup Check and set up the prerequisites and the AWS sign-in, without starting a run
+reframe status The run's stage, the job's plan steps, any waiting question and the next step
+reframe events The run's event log
+reframe answer Show AWS's waiting question, or answer it
+reframe resume Continue a run that stopped; nothing with a receipt is repeated
+reframe report Build the HTML report from the run's downloads again
+reframe claude The Claude assessment: assess the same snapshot with Claude's code-modernization plugin,
+show it in the same business review, load its graph into the run's Neptune cluster, and
+compare it with AWS Transform's results
+reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude
+only, every rule) against the source code, with evidence Reframe checks, then write
+recommended requirements, one SME list and the reconciliation page; needs the run's
+assessments done, and no AWS resources
+reframe review Read the review downloads in a folder and show each reviewer's coverage, sign-offs and
+where reviewers disagree; runs nothing, and the next reframe reconcile --context with
+the same folder combines them
+reframe export Write a run's results for other tools: the reconciled results as one Excel workbook
+(xlsx), or the design's capabilities as a backlog to import into Jira or Azure DevOps,
+with acceptance criteria; runs nothing
+reframe design The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,
+final specifications and the AI-DLC package, from the reconciled results; a round redoes
+only what new context touches
+reframe compare Build the page comparing AWS Transform's and Claude's results again
+reframe publish Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder
+others can open, upload the run's source, results and reports to your account's private
+bucket, or publish the copy to a GitHub Pages site
+reframe reports The reports published to your AWS account: list them, open one with your AWS sign-in, or
+remove the bucket
+reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them
+
+Examples
+reframe the home screen: your runs, the next step and a menu
+reframe run a guided run: checks the prerequisites, the AWS
+sign-in and the source, then starts
+reframe run --source <folder | file.zip | github-url>start straight away, with no questions
+reframe run --tools claude --source <source> Claude only: no AWS account, nothing to tear down
+reframe status where the latest run is, and what to do next
+reframe answer AWS's waiting question, in interactive mode
+reframe report --open open the business review in the browser
+reframe claude the Claude assessment: the same snapshot, assessed
+with Claude as well
+reframe compare --open open the page comparing AWS Transform and Claude
+reframe export --to xlsx the reconciled requirements and business rules as an
+Excel workbook
+reframe design --open the design: screens, journeys, the prototype, final
+specifications and the AI-DLC package
+reframe publish --to aws upload the run's source, results and cleaned reports
+to your account's private bucket
+reframe reports list the published reports; reframe reports open
+<project> opens the latest
+reframe teardown remove the AWS resources the run created
+
+Options
+--version show program's version number and exit
+-h, --help this help
+reframe <command> --help shows a command's options.
diff --git a/src/reframe/claude/graph.py b/src/reframe/claude/graph.py
index 1ff1509c..a5159a6b 100644
--- a/src/reframe/claude/graph.py
+++ b/src/reframe/claude/graph.py
@@ -114,7 +114,8 @@ def build(run: str, sha256: str, model: dict[str, Any], generated: dict[str, Any
for ident in step.get("nodes") or []:
if ident in node_iri:
q.add(s, "involves", node_iri[ident], literal=False)
- modules_by_name = {m.get("name", "").upper(): node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri}
+ from reframe.claude.retrieve import module_keys
+ modules_by_name = {key: node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri for key in module_keys(m)}
rule_iri = {}
for card in model.get("rules") or []:
r = q.iri("rule", card["id"])
diff --git a/src/reframe/claude/requirements.py b/src/reframe/claude/requirements.py
index 3163f196..521e9a1a 100644
--- a/src/reframe/claude/requirements.py
+++ b/src/reframe/claude/requirements.py
@@ -61,7 +61,8 @@
def domain_input(model: dict[str, Any], domain: dict[str, Any]) -> dict[str, Any]:
modules = [m for m in model.get("modules") or [] if m.get("domain") == domain["id"]]
- names = {m.get("name", "").upper() for m in modules}
+ from reframe.claude.retrieve import module_keys
+ names = {key for m in modules for key in module_keys(m)}
members = set(domain.get("members") or [])
rules = [r for r in model.get("rules") or [] if r.get("domain") == domain["id"] or r.get("program", "").upper() in names]
rule_ids = {r["id"] for r in rules}
diff --git a/src/reframe/claude/retrieve.py b/src/reframe/claude/retrieve.py
index 04707040..494340cd 100644
--- a/src/reframe/claude/retrieve.py
+++ b/src/reframe/claude/retrieve.py
@@ -37,13 +37,37 @@ def sections(markdown: str, level: int = 2) -> list[dict[str, str]]:
return out
-def program_of(path: str) -> str:
- """The program name a source path stands for: the file's stem, upper-cased (COBOL member names)."""
+def program_of(path: str, family: str = "mainframe") -> str:
+ """The program name a source path stands for (docs/any-legacy.md, section 5.2). For the mainframe, the file's stem,
+ upper-cased, as COBOL members are named. For any other family, the file's path within the source, so two files of the
+ same name in different folders stay apart."""
+ if family != "mainframe":
+ return path_key(path)
stem = Path(path).name.split(".")[0]
return stem.upper()
-def parse_rules(markdown: str) -> list[dict[str, Any]]:
+def path_key(path: str) -> str:
+ """A source path as Reframe compares it: forward slashes, no leading `./` or `/`."""
+ return path.replace("\\", "/").lstrip("/").removeprefix("./")
+
+
+def module_keys(module: dict[str, Any]) -> set[str]:
+ """What a rule card's program may name a module of the plugin's map by, upper-cased: the module's name (a mainframe
+ member's), and its file's path (any other family's program name)."""
+ keys = {str(module.get("name") or "").upper()} - {""}
+ if module.get("file"):
+ keys.add(path_key(str(module["file"])).upper())
+ return keys
+
+
+def family(folder: RunFolder) -> str:
+ """The run's family from its stack profile (L1-01); a run from before the profile is a mainframe run."""
+ from reframe.source import profile
+ return str((folder.load(profile.FILE) or {}).get("family") or "mainframe")
+
+
+def parse_rules(markdown: str, family: str = "mainframe") -> list[dict[str, Any]]:
cards = []
matches = list(RULE.finditer(markdown))
for i, match in enumerate(matches):
@@ -74,7 +98,7 @@ def parse_rules(markdown: str) -> list[dict[str, Any]]:
"id": match.group(1), "name": match.group(2).strip(), "category": fields.get("category", ""),
"priority": fields.get("priority", "").split(" ")[0], "source": source.strip("` "), "path": path,
"line": int(where.group(2)) if where else None, "line_end": int(where.group(3)) if where and where.group(3) else None,
- "program": program_of(path) if path else "", "plain": fields.get("plain english", ""),
+ "program": program_of(path, family) if path else "", "plain": fields.get("plain english", ""),
"spec": [{"clause": c, "text": t} for c, t in spec], "parameters": fields.get("parameters", ""),
"edge_cases": fields.get("edge cases handled", ""), "defect": fields.get("suspected defect", ""),
"confidence": level, "confidence_note": confidence[len(level):].strip(" —-") if confidence else ""})
@@ -146,10 +170,10 @@ def text(name: str) -> str:
if topology.get("root"):
walk(topology["root"], None, parts)
rules_md = text("BUSINESS_RULES.md")
- cards = parse_rules(rules_md)
- module_domain = {m["name"].upper(): m["domain"] for m in parts["modules"] if m.get("name")}
+ cards = parse_rules(rules_md, family(folder))
+ module_domain = {key: m["domain"] for m in parts["modules"] for key in module_keys(m)}
for card in cards:
- card["domain"] = module_domain.get(card["program"], "")
+ card["domain"] = module_domain.get(card["program"].upper(), "")
result = json.loads(text("rules_result.json") or "{}") if (analysis / "rules_result.json").exists() else {}
stats = result.get("stats") if isinstance(result, dict) else None
return {
diff --git a/src/reframe/core/cli.py b/src/reframe/core/cli.py
index afb4ba68..8c35d140 100644
--- a/src/reframe/core/cli.py
+++ b/src/reframe/core/cli.py
@@ -11,6 +11,7 @@
import sys
from reframe import __version__
+from reframe.source.profile import FAMILIES
# how Claude signs in; the same as reframe.claude.preflight.AUTHS, kept here so the CLI starts without loading it
AUTHS = ("subscription", "api-key", "bedrock")
@@ -42,16 +43,16 @@ def _run_option(parser: argparse.ArgumentParser) -> None:
def parser() -> argparse.ArgumentParser:
from reframe.core.helptext import Parser
- top = Parser(prog="reframe", description="Run an AWS Transform mainframe assessment end to end and bring back its requirements.")
+ top = Parser(prog="reframe", description="From legacy source to reviewed requirements, business rules and a design to build from: with Claude, and for mainframe code with AWS Transform beside it.")
top.add_argument("--version", action="version", version=f"reframe {__version__}")
commands = top.add_subparsers(dest="command", metavar="")
def command(name: str, help: str) -> argparse.ArgumentParser:
return commands.add_parser(name, help=help, description=help)
- run = command("run", "Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no "
+ run = command("run", "Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no "
"options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown")
- run.add_argument("--source", help="the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked "
+ run.add_argument("--source", help="the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked "
"and the prerequisites are assumed to be set up")
run.add_argument("--profile", help="the AWS CLI profile to sign in with (default: the one saved by the guided setup)")
run.add_argument("--ref", help="for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD)")
@@ -66,6 +67,9 @@ def command(name: str, help: str) -> argparse.ArgumentParser:
run.add_argument("--tools", choices=("both", "claude", "aws"), default="both",
help="both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: "
"AWS Transform only (reframe claude adds Claude later)")
+ run.add_argument("--legacy", choices=FAMILIES, default=None,
+ help="the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, "
+ "section 4); AWS Transform is offered only for mainframe")
run.add_argument("--max-agents", type=int, help="the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo)")
run.add_argument("--auth", choices=AUTHS, default=None,
help="how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock "
diff --git a/src/reframe/core/commands/reading.py b/src/reframe/core/commands/reading.py
index a75e9336..368e4772 100644
--- a/src/reframe/core/commands/reading.py
+++ b/src/reframe/core/commands/reading.py
@@ -37,9 +37,12 @@ def status(args) -> int:
ui.hint(f"{state.get('source')} · {state.get('mode')} mode" + (" · Claude only, no AWS" if alone else "")
+ (f" · worker running (process {pid})" if pid else ""))
ui.state("Status", f"{state.get('status')} · stage {state.get('stage')}", STATUS_STYLE.get(str(state.get("status")), "bold yellow"))
- from reframe.source import package_check
+ from reframe.source import package_check, profile
+ stack = folder.load(profile.FILE)
+ if stack:
+ ui.state("Stack", profile.summary(stack), "")
checked = folder.load(package_check.FILE)
- if checked:
+ if checked and (not stack or stack.get("family") == "mainframe"): # what AWS Transform makes of it: mainframe code only
ui.state("Package check", package_check.summary(checked), "")
for note in checked.get("notes", [])[1:]:
ui.hint(note)
diff --git a/src/reframe/core/commands/starting.py b/src/reframe/core/commands/starting.py
index ef8b90e5..64232c0d 100644
--- a/src/reframe/core/commands/starting.py
+++ b/src/reframe/core/commands/starting.py
@@ -20,7 +20,12 @@ def run(args) -> int:
if getattr(args, "tools", "both") == "claude":
return commands.start_claude_only(source=args.source, ref=args.ref, mode=args.mode, project=args.project, foreground=args.foreground,
max_agents=getattr(args, "max_agents", None), auth=auth,
- profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None)
+ profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None,
+ legacy=getattr(args, "legacy", None))
+ legacy = getattr(args, "legacy", None)
+ if legacy and legacy != "mainframe": # AWS Transform is offered only for the mainframe (docs/any-legacy.md, section 5.1)
+ return commands._fail(Stop(Outcome.REFUSED, f"--legacy {legacy}: AWS Transform writes requirements only for mainframe code, so "
+ f"this run is Claude only: reframe run --tools claude --legacy {legacy} --source {args.source}"))
from reframe.core.setup import load_config
saved = load_config()
profile = args.profile or saved.get("profile")
@@ -29,11 +34,11 @@ def run(args) -> int:
both = getattr(args, "tools", "both") == "both" # the Claude assessment alongside, as the guided run offers by default
return commands.start(source=args.source, profile=profile, ref=args.ref, mode=args.mode, region=args.region or saved.get("region") or "us-east-1",
project=args.project, graph=args.graph, terraform=args.terraform, foreground=args.foreground,
- claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None)
+ claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=legacy)
def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, project: str | None, graph: str | None,
- terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None) -> int:
+ terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None, legacy: str | None = None) -> int:
"""Stage 0 and the Neptune choice here, then stages 1 to 8 in a background worker (or this terminal)."""
from reframe.core import pipeline, ui
from reframe.source.snapshot import kind
@@ -45,7 +50,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str,
except (Stop, ReframeError) as error:
return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error)))
folder.update(project=project, source=source, ref=ref, mode=mode, graph_arg=graph, profile=profile,
- region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING")
+ region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING",
+ **({"legacy": legacy} if legacy else {}))
ui.section(f"Run {folder.root.name}")
ui.hint(f"{project} · {mode} mode · run folder {folder.root}")
ctx = pipeline.Context.load(folder)
@@ -75,7 +81,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str,
def start_claude_only(*, source: str, ref: str | None, mode: str, project: str | None, foreground: bool,
- max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None) -> int:
+ max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None,
+ legacy: str | None = None) -> int:
"""A Claude-only run (docs/release-1.md, section 2): the snapshot and the Claude assessment, in one commands.worker, with no AWS resources.
With Amazon Bedrock, the AWS profile (or a Bedrock API key) is used to sign Claude in, and for nothing else."""
from reframe.claude import pipeline as claude_pipeline
@@ -89,7 +96,7 @@ def start_claude_only(*, source: str, ref: str | None, mode: str, project: str |
except (Stop, ReframeError) as error:
return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error)))
folder.update(tools="claude", project=project, source=source, ref=ref, mode=mode, started_at=iso(), stage="snapshot", status="RUNNING",
- **({"profile": profile, "region": region or "us-east-1"} if profile else {}))
+ **({"profile": profile, "region": region or "us-east-1"} if profile else {}), **({"legacy": legacy} if legacy else {}))
claude_pipeline.request(pipeline.Context.load(folder), auth=auth, max_agents=max_agents, mode=mode)
ui.section(f"Run {folder.root.name} · Claude only")
signin = {"subscription": "your Claude subscription", "api-key": "your Anthropic API key",
diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py
index 0df87742..267ca206 100644
--- a/src/reframe/core/guide.py
+++ b/src/reframe/core/guide.py
@@ -184,7 +184,7 @@ def _reachable(url: str) -> str | None:
def source() -> tuple[str, str | None] | None:
from reframe.source.snapshot import URL
ui.section("3 Source")
- form = ui.choose("Where is the mainframe source?", [("A GitHub or Git URL", "https://github.com//"),
+ form = ui.choose("Where is the legacy source?", [("A GitHub or Git URL", "https://github.com//"),
("A local folder", "a Git checkout or a plain folder"),
("A local ZIP file", "")], setup.load_config().get("source_form") or 1)
if form == 1:
@@ -211,6 +211,26 @@ def check_url(value: str) -> str | None:
return str(Path(archive).expanduser().resolve()), None
+def stack(chosen_source: str) -> tuple[str | None, str | None]:
+ """The stack profile of a local source (L1-01), shown before the run starts; asked only when no family carries most of
+ the code. Returns the family (None when it is not known yet) and what the person chose (None to keep what was found).
+ A Git URL is profiled after the snapshot."""
+ from reframe.source import profile
+ path = Path(chosen_source)
+ if not path.exists():
+ ui.hint("The stack profile is worked out after the snapshot; reframe status shows it.")
+ return None, None
+ with ui.console.status("Working out the stack…"):
+ found = profile.profile_folder(path) if path.is_dir() else profile.profile_archive(path)
+ ui.state("Stack", profile.summary(found), "")
+ if found["found"] != "mixed":
+ return found["found"], None
+ families = list(profile.FAMILIES)
+ picked = ui.choose("No family carries most of the code. Which is it?", [(f, "") for f in families], len(families))
+ told = families[picked - 1]
+ return told, None if told == "mixed" else told
+
+
# ---- 4 and 5. choices, summary, start ----------------------------------------------------------------
@@ -355,13 +375,14 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
+ _, legacy = stack(chosen)
picked = claude_only_choices(chosen)
if not claude_only_summary(chosen, ref, picked):
ui.hint("Nothing was started or created.")
return 0
return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"],
foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"],
- auth=picked["claude"]["auth"])
+ auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {}))
if not prerequisites(m):
return 1
sign = sign_in()
@@ -371,6 +392,16 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
+ family, legacy = stack(chosen)
+ if family and family != "mainframe": # AWS Transform is not offered (docs/any-legacy.md, section 5.1)
+ ui.warn("AWS Transform writes requirements only for mainframe code, so this run is Claude only, with no AWS.")
+ picked = claude_only_choices(chosen)
+ if not claude_only_summary(chosen, ref, picked):
+ ui.hint("Nothing was started or created.")
+ return 0
+ return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"],
+ foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"],
+ auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {}))
picked = choices(chosen)
if not summary(chosen, ref, sign, picked):
ui.hint("Nothing was started or created.")
@@ -380,7 +411,8 @@ def run(args) -> int:
ui.hint("Stopped. Nothing was started or created.")
return 130
return commands.start(source=chosen, profile=sign.profile, ref=ref, mode=picked["mode"], region=sign.region, project=picked["project"],
- graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude"))
+ graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude"),
+ **({"legacy": legacy} if legacy else {}))
def setup_only(args) -> int:
diff --git a/src/reframe/core/pipeline.py b/src/reframe/core/pipeline.py
index 282821c0..78a00d0f 100644
--- a/src/reframe/core/pipeline.py
+++ b/src/reframe/core/pipeline.py
@@ -99,6 +99,20 @@ def prepare(ctx: Context, prompt: Callable[[str], str] | None, say: Callable[[st
# ---- the worker ----------------------------------------------------------------------------------
+NOT_MAINFRAME = ("AWS Transform writes requirements and business rules only for mainframe code (docs/any-legacy.md, section 5.1), "
+ "and this codebase's stack profile is {family}: {summary}. Nothing was created in AWS. Assess it with Claude only: "
+ "reframe run --tools claude --source {source}")
+
+
+def refuse_unless_mainframe(folder: RunFolder) -> None:
+ """Stage 1's end: pipeline 1 goes on only for a mainframe codebase, before anything is made in AWS (L1-02)."""
+ from reframe.source import profile
+ stack = folder.load(profile.FILE)
+ if stack and stack.get("family") != "mainframe":
+ raise Stop(Outcome.REFUSED, NOT_MAINFRAME.format(family=stack["family"], summary=profile.summary(stack),
+ source=folder.state.get("source", "")))
+
+
def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome:
"""Stages 1 to 8. Returns DONE, or raises Stop with the outcome to record. on_resources runs once the run's AWS
resources exist (pipeline 2 starts there, alongside this pipeline)."""
@@ -108,6 +122,7 @@ def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome
names = ctx.names()
ctx.stage("snapshot")
record = snapshot.take(ctx.folder, state["source"], state.get("ref"))
+ refuse_unless_mainframe(ctx.folder)
ctx.stage("infrastructure")
tf = ctx.terraform()
diff --git a/src/reframe/core/ui.py b/src/reframe/core/ui.py
index d1a81bd8..15adc2c6 100644
--- a/src/reframe/core/ui.py
+++ b/src/reframe/core/ui.py
@@ -24,7 +24,7 @@
def header(subtitle: str = "AWS Transform · Claude · Reconciliation · Design") -> None:
content = Text("REFRAME\n", style="bold bright_cyan")
- content.append("From mainframe source to reviewed requirements, business rules and a design to build from\n", style="bold white")
+ content.append("From legacy source to reviewed requirements, business rules and a design to build from\n", style="bold white")
content.append(STEPS, style="dim")
console.print(Panel(content, border_style="cyan", padding=(1, 2), subtitle=subtitle))
diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py
index e8a0f032..381aa9ef 100644
--- a/src/reframe/design/designpage.py
+++ b/src/reframe/design/designpage.py
@@ -16,6 +16,7 @@
PAGE = "outputs/design/index.html"
EXTRA = """
+.note{background:var(--card);border:1px solid var(--line);border-left:4px solid var(--warn);border-radius:8px;padding:10px 14px}
.tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin:14px 0}
.tile{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:10px 12px}.tile b{display:block;font-size:22px}
.tile span{color:var(--muted);font-size:13px}
@@ -148,8 +149,9 @@ def draw(folder, value: dict[str, Any]) -> Path:
c, m = value["counts"], (modern.get("counts") or {})
how = ", ".join(f"{n} {h}" for h, n in (m.get("how") or {}).items() if n)
stack = value.get("stack") or {}
- tiles = [(len(inventory.get("screens") or []), "legacy screens"), (len(modern.get("screens") or []), "modern screens"), (len(journeys), "journeys"),
- (m.get("mapped", 0), "legacy items mapped"), (c["capabilities"], "capabilities"), (c["final"], "final"), (c["draft"], "draft"),
+ left_out = modern.get("left_out") or "" # a codebase with no screens (L1-04)
+ tiles = ([] if left_out else [(len(inventory.get("screens") or []), "legacy screens"), (len(modern.get("screens") or []), "modern screens"),
+ (len(journeys), "journeys"), (m.get("mapped", 0), "legacy items mapped")]) + [(c["capabilities"], "capabilities"), (c["final"], "final"), (c["draft"], "draft"),
(c["requirements"], "requirements"), (c["criteria"], "acceptance criteria"), (c["contracts"], "data contracts"), (c["gaps"], "decision table gaps"),
(c["questions"], "open SME questions")]
domains: dict[str, dict[str, list[dict[str, Any]]]] = {}
@@ -167,11 +169,23 @@ def draw(folder, value: dict[str, Any]) -> Path:
if stack else "Target stack: not given yet, so the data contracts show neutral types.")
notes = " ".join(e(n) for n in value.get("stack_notes") or [] if stack)
contracts = "".join(contract_block(x) for x in value["contracts"].values())
+ contracts_how = ("The tables and entities the capabilities' code uses, as typed records: the tables read from the SQL DDL with no model, the "
+ "entities by a Claude step whose every cited line Reframe checked." if any(x.get("kind") for x in value["contracts"].values()) else
+ "The copybooks the capabilities' programs copy, as typed records, read from the source with no model.")
+ nav = (f'
' 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
@@ -183,7 +197,7 @@ def draw(folder, value: dict[str, Any]) -> Path:
{''.join(body_parts)}
-
Data contracts
The copybooks the capabilities' programs copy, as typed records, read from the source with no model.
{contracts}
+
Data contracts
{contracts_how}
{contracts}
What the checks still found
{problems}{more}
"""
target = folder.path(PAGE)
diff --git a/src/reframe/design/flowpage.py b/src/reframe/design/flowpage.py
index 54e77e35..673007b7 100644
--- a/src/reframe/design/flowpage.py
+++ b/src/reframe/design/flowpage.py
@@ -15,7 +15,8 @@
from reframe.design.legacy import STYLE
PAGE = "outputs/design/flow.html"
-KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction"}
+KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction",
+ "href": "link", "form": "form", "redirect": "redirect", "renders": "renders"} # the last four: the general reader's (L1-05)
def _cites(lines: list[str]) -> str:
@@ -160,15 +161,20 @@ def draw(folder, screens: dict[str, Any], found: dict[str, Any]) -> Path:
+ (f" · from {', '.join(_target(c, screens_of, titles) for c in comes)}" if comes else "") + "
"
+ ('
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/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/package.py b/src/reframe/design/package.py
index f90ac536..11819008 100644
--- a/src/reframe/design/package.py
+++ b/src/reframe/design/package.py
@@ -65,7 +65,7 @@
"Use synthetic data only; never copy production or personal data.",
"Keep the copybook and field names in a comment or mapping, so the legacy data can be migrated and compared."]),
"api": ("API", "Builds the services and scheduled jobs the capability runs as, from the design notes.",
- ["Follow each design note; the mainframe mechanics (VSAM, CICS, JCL, COMMAREA) are not to be copied.",
+ ["Follow each design note; the legacy platform's mechanics (on a mainframe: VSAM, CICS, JCL, COMMAREA) are not to be copied.",
"A capability that runs as a scheduled job becomes a job with the same inputs, outputs and failure handling.",
"Name the rules and requirements each endpoint or job implements."]),
"test-generation": ("Test generation", "Writes an automated test for every acceptance criterion, named by its ID.",
@@ -175,7 +175,7 @@ def add(role: str, title: str, qs: list[dict[str, Any]], details: list[str], dep
add("business-rules", "Implement error handling and messages", by_class["error handling"] + by_class["formatting"],
["Show every message word for word; formatting rules may be restyled to the design system."], first)
shape = {"online": "the services behind the screens", "scheduled job": "the scheduled job", "online and scheduled job": "the services and the scheduled job",
- "service": "the service"}[s["runs_as"]]
+ "service": "the service", "library": "the library the rest of the application calls"}[s["runs_as"]]
notes = [f"{rid.get(n['rule'], n['rule'])}: {n['note']}" for n in s["design_notes"]]
add("api", f"Build {shape}", by_class["design note"] or (reqs if s["runs_as"] != "online" and not s["screens"] else []), notes or ["Expose the rules as the service the screens call."],
[t["id"] for t in found if t["role"] in ("data", "business-rules")])
@@ -393,7 +393,7 @@ def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
def role_md(role: str) -> str:
name, what, rules = ROLES[role]
- return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized mainframe application.",
+ return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized legacy application.",
"", what, "", "## Template", "", "For each task you take: read the task's requirements, rules and criteria by ID in the specification; "
"do the work; name the IDs you implemented; list what you could not do and why.", "", "## Guardrails", ""]
+ [f"- {r}" for r in rules] + ["- The legacy source is read-only. Use synthetic data only.", "- A draft capability is confirmed with the owner before it is built.", ""]
@@ -474,11 +474,11 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
tech = "# Tech\n\n## Target stack\n\n" + stack_md(stack, context.get("architecture", "")) + "\n"
files: dict[str, str] = {}
known = handover.facts(specs, journeys, programs or {})
- files["START-HERE.md"] = handover.start_here(known, project, stack, None)
+ files["START-HERE.md"] = handover.start_here(known, project, stack, None, context.get("legacy", ""))
kept = [d for d in datasets.values() if d["cases"] or d["uncovered"]]
comparer = Path(golden_compare.__file__).read_text()
for form in FORMS:
- files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form)
+ files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form, context.get("legacy", ""))
files[f"{form}/data-contracts.md"] = contracts
files[f"{form}/traceability.md"] = trace
files[f"{form}/golden/README.md"] = golden.readme(kept)
@@ -502,10 +502,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
files[f"{base}/design.md"] = design_md(s, books)
files[f"{base}/tasks.md"] = tasks_md(s, ts[s["id"]])
# Claude Code
+ has_ui = bool(prototype and prototype.is_file()) # a codebase with no screens has no prototype (L1-04)
index = "\n".join(f"- [{s['id']} {md(s['title'])}](specs/{s['folder']}.md): {s['status']}, {s['runs_as']}" for s in specs)
files["claude-code/CLAUDE.md"] = "\n".join([
f"# {project}, modernized", "", "Build the modernized application from the specifications here. Each capability's specification is in `specs/`; "
- "the build tasks, each for a role, are in `tasks.md`; the prototype in `ui-reference/index.html` is the UI to build to; the data contracts are in "
+ "the build tasks, each for a role, are in `tasks.md`; " + ("the prototype in `ui-reference/index.html` is the UI to build to; " if has_ui else
+ "the legacy codebase has no screens, so there is no prototype: the capabilities run as jobs or services; ") + "the data contracts are in "
"`data-contracts.md`; `traceability.md` takes every ID back to the legacy source.", "", "## Target stack", "", stack_md(stack, context.get("architecture", "")), "",
"## Conventions", ""] + conventions() + ["", "## House conventions", "", handover.house(context.get("style", "")), "",
"## Skills", "", "In `.claude/skills/`: " + ", ".join(f"`{n}`" for n in handover.SKILLS) + ". Fill in their placeholders first; START-HERE.md says how.", "",
@@ -514,7 +516,8 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n"
for s in specs:
files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books)
- files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. "
+ if has_ui:
+ files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. "
"Each screen is a route (`#/`); *Show the legacy screen* shows the 3270 screen it replaces.\n")
# Spec Kit
files["spec-kit/.specify/memory/constitution.md"] = "\n".join([
@@ -653,7 +656,7 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
books = (folder.load("design/contracts.json") or {}).get("contracts") or {}
stack = folder.load(STACK) or None
journeys = (folder.load("design/journeys.json") or {}).get("journeys") or []
- prototype = folder.path("outputs/design/prototype/index.html")
+ prototype = None if (folder.load("design/modern.json") or {}).get("left_out") else folder.path("outputs/design/prototype/index.html")
project = folder.state.get("project") or "the application"
have = versions(folder)
latest = folder.path(f"{FOLDER}/v{have[-1]}") if have else None
@@ -661,7 +664,10 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
root = Path(tmp) / "package"
inventory = (folder.load("design/screens.json") or {}).get("screens") or []
programs = {s["map"]: [p["name"] for p in s.get("programs") or []] for s in inventory}
- ts = write(root, specs, books, stack, journeys, prototype, project, read_context(context), programs)
+ from reframe.source import profile
+ stack_profile = profile.of_run(folder) # START-HERE names the stack (docs/any-legacy.md, section 5.5)
+ told = {**read_context(context), "legacy": f"{stack_profile['words']['languages']}, {stack_profile.get('family', 'mainframe')}"}
+ ts = write(root, specs, books, stack, journeys, prototype, project, told, programs)
problems = check(root, specs, ts)
made = manifest(specs, ts, stack)
same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root)
diff --git a/src/reframe/design/pipeline.py b/src/reframe/design/pipeline.py
index f1c4d961..44a399ed 100644
--- a/src/reframe/design/pipeline.py
+++ b/src/reframe/design/pipeline.py
@@ -223,6 +223,9 @@ def changes_md(n: int, report: dict[str, Any]) -> str:
out += ["## The context", ""] + [f"- Added {f}" for f in ctx["added"]] + [f"- Changed {f}" for f in ctx["changed"]] + [f"- Removed {f}" for f in ctx["removed"]] + [""]
for stage, title in (("journeys", "Journeys"), ("screens", "Modern screens"), ("specs", "Final specifications")):
r = report["stages"].get(stage) or {"redone": [], "kept": []}
+ if r.get("left_out"):
+ out += [f"## {title}", "", "- Left out: the codebase has no screens.", ""]
+ continue
out += [f"## {title}", ""]
out += [f"- Made: {x['name'] or 'No domain'} (new)." if x["changed"] == ["new"] else f"- Redone: {x['name'] or 'No domain'}, because {words(stage, x['changed'])}."
for x in r["redone"]]
@@ -242,6 +245,19 @@ def changes_md(n: int, report: dict[str, Any]) -> str:
return "\n".join(out).rstrip() + "\n"
+def without_screens(stack: dict[str, Any], found: dict[str, Any]) -> str:
+ """Why the design has no screens (L1-04, docs/any-legacy.md section 5.4), or "" when it has some: no reader found a
+ screen and the stack profile found no screen definitions, views, templates or forms."""
+ if found.get("screens") or (stack.get("has") or {}).get("ui", {}).get("count"):
+ return ""
+ has = stack.get("has") or {}
+ what = ("a batch system" if has.get("jobs", {}).get("count") and not has.get("routes", {}).get("count")
+ else "a service" if has.get("routes", {}).get("count") else "a library")
+ return (f"This codebase has no screens: it looks like {what}, and Reframe found no screen definitions, views, templates or forms in it. "
+ "The journeys, the modern screens and the prototype are left out; the final specifications, golden datasets, package and "
+ "backlog are written as for any codebase.")
+
+
def run(folder, claude, context: Path | None = None, stack: str | None = None, plan_only: bool = False) -> dict[str, Any]:
from reframe.claude.workspace import paths
from reframe.design import designpage, flow, flowpage, inventory, journeypage, journeys, legacy, modernpage, package, prototype, screens, specs
@@ -259,33 +275,56 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p
"context_files": {"added": sorted(set(got["files"]) - set(before)), "removed": sorted(set(before) - set(got["files"])),
"changed": sorted(f for f in got["files"] if f in before and before[f] != got["files"][f])},
"signoffs": got["signoffs"], "journey_signoffs": got["journey_signoffs"], "ignored": got["ignored"]}
+ from reframe.source import profile
+ left_out = without_screens(profile.of_run(folder), inventory.inventory(paths(folder)["legacy"]))
if plan_only:
- report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"]
- report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"]
- report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"])["round"]
+ if left_out:
+ report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out}
+ else:
+ report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"]
+ report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"]
+ report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"], screenless=bool(left_out))["round"]
report["note"] = "Screens and specifications whose journeys or screens a redone part changes are redone too; this plan cannot see those yet."
return report
folder.update(design={**state, "round": number, "status": "running", "context": str(context) if context else "", "started_at": iso()})
legacy_folder = paths(folder)["legacy"]
- found = inventory.inventory(legacy_folder)
- folder.save("design/screens.json", found)
+ stack_profile = profile.of_run(folder)
+ if stack_profile.get("family", "mainframe") == "mainframe": # the exact readers: BMS maps and CICS, with no model
+ found = inventory.inventory(legacy_folder)
+ folder.save("design/screens.json", found)
+ linked = flow.flow(legacy_folder, found)
+ linked["problems"] = flow.check(linked, legacy_folder)
+ else: # the general reader (L1-05): fields and actions by a checked Claude step; links by pattern, then a checked step
+ from reframe.design import general
+ views = profile.files_with(legacy_folder, "ui")
+ found = general.read_screens(folder, claude, legacy_folder, views, stack_profile["words"]["languages"]) if views else \
+ {"reader": "general", "screens": [], "maps": 0, "mapsets": 0, "fields": 0, "problems": 0}
+ linked = general.read_flow(folder, claude, legacy_folder, found, stack_profile)
+ linked["problems"] = general.check(linked, legacy_folder)
+ found.pop("round", None)
+ folder.save("design/screens.json", found)
+ report["reader"] = {"screens": found.get("steps", 0), "links": linked["counts"]}
+ left_out = without_screens(stack_profile, found)
legacy.draw_all(folder, found)
- linked = flow.flow(legacy_folder, found)
- linked["problems"] = flow.check(linked, legacy_folder)
folder.save("design/flow.json", linked)
flowpage.draw(folder, found, linked)
- value = journeys.run(folder, claude, context, for_journeys)
- journeypage.draw(folder, value)
- report["stages"]["journeys"] = value["round"]
- for_journeys, for_screens, for_specs = routers(folder, got, routed)
- value = screens.run(folder, claude, context, for_screens)
- modernpage.draw(folder, value)
- report["stages"]["screens"] = value["round"]
- data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"),
- (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "")
- prototype.draw(folder, data, got["tokens"])
+ if left_out: # a batch system, a service or a library: no journeys, modern screens or prototype, and the page says why
+ folder.save("design/journeys.json", {"journeys": [], "left_out": left_out})
+ folder.save("design/modern.json", {"screens": [], "domains": {}, "counts": {}, "left_out": left_out})
+ report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out}
+ else:
+ value = journeys.run(folder, claude, context, for_journeys)
+ journeypage.draw(folder, value)
+ report["stages"]["journeys"] = value["round"]
+ for_journeys, for_screens, for_specs = routers(folder, got, routed)
+ value = screens.run(folder, claude, context, for_screens)
+ modernpage.draw(folder, value)
+ report["stages"]["screens"] = value["round"]
+ data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"),
+ (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "")
+ prototype.draw(folder, data, got["tokens"])
for_journeys, for_screens, for_specs = routers(folder, got, routed)
- value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"])
+ value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"], screenless=bool(left_out))
designpage.draw(folder, value)
report["stages"]["specs"] = value["round"]
report["problems"] = value["problems"]
diff --git a/src/reframe/design/schema.py b/src/reframe/design/schema.py
new file mode 100644
index 00000000..3a4a54e6
--- /dev/null
+++ b/src/reframe/design/schema.py
@@ -0,0 +1,320 @@
+"""Pipeline 4, stage D6 for any stack: data contracts from the schema and the entities (L1-06, docs/any-legacy.md 5.4).
+
+For a codebase that is not a mainframe, the contracts come from what the stack profile found as data:
+
+- **SQL DDL,** read with no model: each `CREATE TABLE` is a record whose fields are its columns, each with its SQL type
+ as written, a neutral type (text of n characters, an integer, a decimal with its digits and scale, floating point, a
+ date, a timestamp, true or false, binary data), whether it may be empty, and its key (primary, or foreign to a table's
+ column), citing the line it is on;
+- **entity and record classes** (JPA, Entity Framework, plain classes the ORM maps), read by one Claude step per batch of
+ files: each entity with its fields, their types as written, the neutral type, the key and whether a value is
+ required, each citing its line. Reframe checks every cited line exists and shows the field's name; an answer that
+ fails is asked again once with the reasons, then the file is kept as unread, never guessed.
+
+The contracts have the copybooks' shape (reframe.design.contracts), so the specifications, the design page and the
+package use them as they are. The target stack's code and column types apply as for copybooks; a date, a timestamp, a
+boolean or binary data keeps its neutral type, since Reframe's type tables do not name those.
+
+A program (a source file, L1-02) uses a contract when its code names the table or the entity.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+FILE = "design/schema.json"
+METHOD = "schema-1"
+BATCH_FILES = 8
+NEUTRAL = ("text", "integer", "decimal", "float", "date", "timestamp", "time", "boolean", "binary")
+CODE = {".java", ".kt", ".groovy", ".cs", ".vb", ".py", ".rb", ".php"}
+
+PROMPT = """Read {input}. It holds entity and record classes of a legacy {languages} application, each with its lines numbered: the classes its code maps to stored data. The legacy source is under {legacy}/ if you need more; do not change anything.
+
+For each file ("files", one entry per file, "file" exactly as listed), give the entities it defines ("entities"): each with its "name" (the class), the "table" it is stored in if the code says (else empty), its "line", and its "fields": each with "name" (as written), "type" (as written), "neutral" (one of text, integer, decimal, float, date, timestamp, time, boolean, binary), "length" (for text, if the code gives one, else 0), "digits" and "scale" (for a decimal, if the code gives them, else 0), "key" ("primary", "foreign" or empty), "required" (true when the code says a value must be given) and "line" (the line the field is declared on).
+
+Use only what the files show. A file with no entity gets an empty list. Answer only with the JSON."""
+
+RETRY = """Your answer failed Reframe's checks. Answer again with the whole JSON, fixing these:
+
+{problems}"""
+
+SCHEMA = {"type": "object", "required": ["files"], "properties": {"files": {"type": "array", "items": {
+ "type": "object", "required": ["file", "entities"], "properties": {"file": {"type": "string"}, "entities": {"type": "array", "items": {
+ "type": "object", "required": ["name", "table", "line", "fields"], "properties": {
+ "name": {"type": "string"}, "table": {"type": "string"}, "line": {"type": "integer"},
+ "fields": {"type": "array", "items": {"type": "object", "required": ["name", "type", "neutral", "length", "digits", "scale", "key", "required", "line"],
+ "properties": {"name": {"type": "string"}, "type": {"type": "string"},
+ "neutral": {"type": "string", "enum": list(NEUTRAL)}, "length": {"type": "integer"},
+ "digits": {"type": "integer"}, "scale": {"type": "integer"},
+ "key": {"type": "string", "enum": ["primary", "foreign", ""]},
+ "required": {"type": "boolean"}, "line": {"type": "integer"}}}}}}}}}}}}
+
+
+# ---- neutral types -----------------------------------------------------------------------------------------------------
+
+def sql_type(written: str) -> dict[str, Any]:
+ """An SQL column type -> Reframe's neutral type."""
+ t = written.upper().strip()
+ m = re.match(r"(\w+(?:\s+(?:VARYING|PRECISION))?)\s*(?:\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\))?", t)
+ name, a, b = (m.group(1), int(m.group(2) or 0), int(m.group(3) or 0)) if m else (t, 0, 0)
+ if name in ("CHAR", "CHARACTER", "VARCHAR", "VARCHAR2", "NVARCHAR", "NCHAR", "CHARACTER VARYING", "TEXT", "CLOB", "STRING"):
+ return {"type": "text", "length": a, "storage": "characters", "bytes": a}
+ if name in ("SMALLINT", "INT", "INTEGER", "BIGINT", "TINYINT", "MEDIUMINT", "SERIAL", "BIGSERIAL"):
+ digits = {"TINYINT": 3, "SMALLINT": 5, "MEDIUMINT": 7, "BIGINT": 19, "BIGSERIAL": 19}.get(name, 10)
+ return {"type": "integer", "digits": digits, "scale": 0, "signed": True, "storage": "binary", "bytes": 8 if digits > 10 else 4}
+ if name in ("DECIMAL", "NUMERIC", "DEC", "NUMBER", "MONEY"):
+ return {"type": "decimal" if b else "integer", "digits": a or 18, "scale": b, "signed": True, "storage": "decimal", "bytes": 0}
+ if name in ("FLOAT", "REAL", "DOUBLE", "DOUBLE PRECISION"):
+ return {"type": "float", "storage": "double float" if name != "REAL" else "single float", "bytes": 8}
+ if name in ("DATE",):
+ return {"type": "date"}
+ if name in ("TIMESTAMP", "DATETIME", "DATETIME2", "TIMESTAMPTZ"):
+ return {"type": "timestamp"}
+ if name in ("TIME",):
+ return {"type": "time"}
+ if name in ("BOOLEAN", "BOOL", "BIT"):
+ return {"type": "boolean"}
+ if name in ("BLOB", "BINARY", "VARBINARY", "BYTEA", "IMAGE"):
+ return {"type": "binary"}
+ return {"type": "unknown"}
+
+
+def from_answer(f: dict[str, Any]) -> dict[str, Any]:
+ kind = f.get("neutral") or "unknown"
+ if kind == "text":
+ return {"type": "text", "length": int(f.get("length") or 0), "storage": "characters", "bytes": int(f.get("length") or 0)}
+ if kind in ("integer", "decimal"):
+ return {"type": kind, "digits": int(f.get("digits") or (18 if kind == "decimal" else 10)), "scale": int(f.get("scale") or 0),
+ "signed": True, "storage": "decimal" if kind == "decimal" else "binary", "bytes": 0}
+ if kind == "float":
+ return {"type": "float", "storage": "double float", "bytes": 8}
+ return {"type": kind}
+
+
+def says(t: dict[str, Any]) -> str:
+ from reframe.design.contracts import describe
+ kind = t.get("type")
+ if kind == "text":
+ return f"text, {t['length']} characters" if t.get("length") else "text"
+ if kind in ("integer", "decimal") and t.get("storage") in ("binary", "decimal"):
+ return (f"integer, {t['digits']} digits" if kind == "integer" else f"decimal, {t['digits'] - t['scale']} integer and {t['scale']} fraction digits")
+ return {"date": "date", "timestamp": "date and time", "time": "time of day", "boolean": "true or false", "binary": "binary data",
+ "unknown": "a type Reframe does not know"}.get(str(kind)) or describe(t)
+
+
+def typed(t: dict[str, Any], types: dict[str, Any]) -> dict[str, str]:
+ from reframe.design.contracts import on_stack
+ if t.get("type") == "text" and not t.get("length"):
+ return {} # a text of no stated length: Reframe gives no column size it was not told
+ return on_stack(t, types)
+
+
+# ---- SQL DDL, with no model --------------------------------------------------------------------------------------------
+
+CREATE = re.compile(r"\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"`\[\]]+)\s*\(", re.I)
+
+
+def _split(body: str) -> list[tuple[str, int]]:
+ """The comma-separated parts of a table body at depth 0, each with its offset."""
+ parts, depth, start = [], 0, 0
+ for i, ch in enumerate(body):
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ elif ch == "," and depth == 0:
+ parts.append((body[start:i], start))
+ start = i + 1
+ parts.append((body[start:], start))
+ return parts
+
+
+def tables(text: str, rel: str, types: dict[str, Any]) -> list[dict[str, Any]]:
+ """Every CREATE TABLE in one file, as contracts."""
+ found = []
+ for m in CREATE.finditer(text):
+ depth, end = 1, m.end()
+ while end < len(text) and depth:
+ depth += {"(": 1, ")": -1}.get(text[end], 0)
+ end += 1
+ body, base = text[m.end():end - 1], m.end()
+ name = m.group(1).strip('"`[]').split(".")[-1]
+ fields, primary, foreign = [], set(), {}
+ for part, offset in _split(body):
+ clause = " ".join(part.split())
+ if not clause:
+ continue
+ line = text[:base + offset + len(part) - len(part.lstrip())].count("\n") + 1
+ pk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?PRIMARY\s+KEY\s*\(([^)]*)\)", clause, re.I)
+ fk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s*REFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", clause, re.I)
+ if pk:
+ primary |= {c.strip().strip('"`').upper() for c in pk.group(1).split(",")}
+ continue
+ if fk:
+ foreign[fk.group(1).strip().strip('"`').upper()] = f"{fk.group(2).strip(chr(34) + '`')}({fk.group(3).strip()})"
+ continue
+ if re.match(r"(CONSTRAINT|UNIQUE|CHECK|INDEX|KEY)\b", clause, re.I):
+ continue
+ col = re.match(r"([\w\"`\[\]]+)\s+(.+)", clause)
+ if not col:
+ continue
+ cname, rest = col.group(1).strip('"`[]'), col.group(2)
+ written = re.match(r"[\w ]+?(?:\([^)]*\))?(?=\s+(?:NOT|NULL|DEFAULT|PRIMARY|REFERENCES|UNIQUE|CHECK|CONSTRAINT|GENERATED|AUTO_INCREMENT|IDENTITY)\b|\s*$)",
+ rest, re.I)
+ sql = (written.group(0) if written else rest.split()[0]).strip()
+ t = sql_type(sql)
+ ref = re.search(r"\bREFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", rest, re.I)
+ if re.search(r"\bPRIMARY\s+KEY\b", rest, re.I):
+ primary.add(cname.upper())
+ if ref:
+ foreign[cname.upper()] = f"{ref.group(1).strip(chr(34) + '`')}({ref.group(2).strip()})"
+ field = {"name": cname, "level": 1, "group": "", "pic": sql, "usage": " ".join(rest[len(sql):].split()), **t, "says": says(t),
+ "line": line, "nullable": not re.search(r"\bNOT\s+NULL\b|\bPRIMARY\s+KEY\b", rest, re.I)}
+ stack = typed(t, types)
+ if stack:
+ field["stack"] = stack
+ fields.append(field)
+ for f in fields:
+ if f["name"].upper() in primary:
+ f["key"] = "primary"
+ elif f["name"].upper() in foreign:
+ f["key"] = f"foreign: {foreign[f['name'].upper()]}"
+ found.append({"copybook": name.upper(), "kind": "table", "file": rel, "how": "SQL DDL, read with no model",
+ "records": [{"name": name, "line": text[:m.start()].count("\n") + 1, "fields": fields}]})
+ return found
+
+
+# ---- entities, by a checked Claude step --------------------------------------------------------------------------------
+
+def _lines(legacy: Path, rel: str) -> list[str]:
+ try:
+ return (legacy / rel).read_text(errors="replace").splitlines()
+ except OSError:
+ return []
+
+
+def problems(answer: dict[str, Any] | None, batch: list[str], legacy: Path) -> list[str]:
+ if not answer or not isinstance(answer.get("files"), list):
+ return ["no answer"]
+ found, seen = [], set()
+ for f in answer["files"]:
+ name = f.get("file")
+ if name not in batch:
+ found.append(f"{name}: not a file of this batch")
+ continue
+ seen.add(name)
+ lines = _lines(legacy, name)
+ for e in f.get("entities") or []:
+ if not 1 <= int(e.get("line") or 0) <= len(lines):
+ found.append(f"{name}: entity {e.get('name')!r} cites line {e.get('line')}, which {name} does not have")
+ for x in e.get("fields") or []:
+ n = int(x.get("line") or 0)
+ if not 1 <= n <= len(lines):
+ found.append(f"{name}: field {x.get('name')!r} cites line {n}, which {name} does not have ({len(lines)} lines)")
+ elif str(x.get("name") or "") not in lines[n - 1]:
+ found.append(f"{name}: field {x.get('name')!r} is not on line {n}")
+ found += [f"{name}: missing from the answer" for name in batch if name not in seen]
+ return found
+
+
+def entities(folder, claude, legacy: Path, files: list[str], words: str, types: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]:
+ """The entity classes of the files, as contracts, and the problems left after the second answer."""
+ from reframe.claude.steps import stop_for
+ from reframe.claude.workspace import paths
+ saved = folder.load(FILE, {}) or {}
+ kept, log = saved.get("entities") or {}, saved.get("log") or []
+ places, project = paths(folder), folder.state["project"]
+ folder_in = places["analysis"] / "reframe" / "design"
+ left: list[str] = []
+ out: list[dict[str, Any]] = []
+ for i in range(0, len(files), BATCH_FILES):
+ batch = files[i:i + BATCH_FILES]
+ data = {"files": [{"file": f, "lines": "\n".join(f"{n:5} {x}" for n, x in enumerate(_lines(legacy, f), 1))} for f in batch]}
+ key = f"b{i // BATCH_FILES + 1}"
+ digest = hashlib.sha256(json.dumps([data, METHOD], sort_keys=True).encode()).hexdigest()[:16]
+ before = kept.get(key) or {}
+ if before.get("hash") != digest or before.get("problems"):
+ if claude is None:
+ left.append(f"{', '.join(batch)}: not read yet")
+ continue
+ folder_in.mkdir(parents=True, exist_ok=True)
+ path = folder_in / f"schema-entities-{key}.json"
+ path.write_text(json.dumps(data, indent=1))
+ prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", languages=words)
+ answer, wrong = None, ["no answer"]
+ for attempt in (1, 2):
+ step = claude.run(f"schema-entities-{key}{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else
+ prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=SCHEMA)
+ log.append({"part": key, "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}})
+ if not step.ok:
+ if step.problem in ("limit", "signin"):
+ folder.save(FILE, {**saved, "entities": kept, "log": log})
+ raise stop_for(step, "the data contracts")
+ wrong = [f"the step did not finish ({step.problem})"]
+ continue
+ answer = claude.structured(step)
+ wrong = problems(answer, batch, legacy)
+ if not wrong:
+ break
+ before = kept[key] = {"hash": digest, "answer": None if wrong else answer, "problems": wrong}
+ folder.save(FILE, {**saved, "entities": kept, "log": log})
+ left += before.get("problems") or []
+ for f in (before.get("answer") or {}).get("files") or []:
+ for e in f.get("entities") or []:
+ fields = []
+ for x in e.get("fields") or []:
+ t = from_answer(x)
+ field = {"name": x["name"], "level": 1, "group": "", "pic": x.get("type", ""), "usage": "required" if x.get("required") else "",
+ **t, "says": says(t), "line": int(x["line"]), "nullable": not x.get("required")}
+ if x.get("key"):
+ field["key"] = x["key"]
+ stack = typed(t, types)
+ if stack:
+ field["stack"] = stack
+ fields.append(field)
+ out.append({"copybook": str(e["name"]).upper(), "kind": "entity", "file": f["file"], "table": e.get("table") or "",
+ "how": "entity class, read by a Claude step Reframe checked", "records": [{"name": e["name"], "line": int(e["line"]), "fields": fields}]})
+ return out, left
+
+
+# ---- all of it ---------------------------------------------------------------------------------------------------------
+
+def read(folder, claude, legacy: Path, stack: dict[str, Any], types: dict[str, Any]) -> dict[str, Any]:
+ """Every contract of a codebase that is not a mainframe: its tables, with no model, and its entities, by a checked step."""
+ from reframe.source import profile
+ data_files = profile.files_with(legacy, "data")
+ found: dict[str, dict[str, Any]] = {}
+ for rel in data_files:
+ if PurePosixPath(rel).suffix.lower() in (".sql", ".ddl"):
+ for c in tables((legacy / rel).read_text(errors="replace"), rel, types):
+ found.setdefault(c["copybook"], c)
+ code = [rel for rel in data_files if PurePosixPath(rel).suffix.lower() in CODE]
+ made, left = entities(folder, claude, legacy, code, stack["words"]["languages"], types)
+ for c in made:
+ name = c["copybook"] if c["copybook"] not in found else f"{c['copybook']}-ENTITY"
+ found[name] = {**c, "copybook": name}
+ return {"contracts": found, "problems": left}
+
+
+def uses(legacy: Path, contracts: dict[str, dict[str, Any]]) -> dict[str, dict[str, str]]:
+ """For each source file (the program, L1-02), the contracts its code names: a table by its name, an entity by its class."""
+ from reframe.source import kinds, profile
+ words = {name: {c["records"][0]["name"], *([c["table"]] if c.get("table") else [])} for name, c in contracts.items()}
+ found: dict[str, dict[str, str]] = {}
+ for p in sorted(legacy.rglob("*")):
+ if not p.is_file():
+ continue
+ rel = p.relative_to(legacy).as_posix()
+ if profile.is_library(rel) or profile.language(rel, kinds.read_head(p)) in (None, "SQL"):
+ continue
+ text = p.read_text(errors="replace")
+ mine = {name: ("table" if c["kind"] == "table" else "entity") for name, c in contracts.items()
+ if c["file"] != rel and any(re.search(rf"\b{re.escape(w)}\b", text, re.I if c["kind"] == "table" else 0) for w in words[name])}
+ mine.update({name: "entity" for name, c in contracts.items() if c["file"] == rel})
+ if mine:
+ found[rel.upper()] = mine
+ return found
diff --git a/src/reframe/design/screens.py b/src/reframe/design/screens.py
index daec4e3a..4fb9c04d 100644
--- a/src/reframe/design/screens.py
+++ b/src/reframe/design/screens.py
@@ -328,7 +328,8 @@ def one(item, across: list[str] | None = None) -> None:
safe = "".join(c if c.isalnum() else "-" for c in (key or "no-domain")).strip("-")[:50]
path = folder_in / f"screens-{safe}{'-links' if across else ''}.json"
path.write_text(json.dumps(data, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
answer, wrong, attempts = None, across or ["no answer"], 0
for attempt in ((3,) if across else (1, 2)): # the links pass: one more ask, with every other domain's screens
attempts = attempt
diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py
index faa0ed87..5773140e 100644
--- a/src/reframe/design/specs.py
+++ b/src/reframe/design/specs.py
@@ -139,13 +139,39 @@ def example_criteria(reqs: list[dict[str, Any]], rules: dict[str, Any]) -> list[
return found
-def runs_as(rules: list[dict[str, Any]], online: set[str]) -> str:
+def what_runs(legacy: Path) -> tuple[set[str], set[str]]:
+ """For any stack but the mainframe (L1-07): the source files of job definitions and of routes, each with the files it
+ uses, by path in capitals (a program's name, L1-02)."""
+ from reframe.design.general import used_files
+ from reframe.source import profile
+ stems: dict[str, list[str]] = defaultdict(list)
+ for item in legacy.rglob("*"):
+ if item.is_file():
+ stems[item.stem].append(item.relative_to(legacy).as_posix())
+ jobs: set[str] = set()
+ routes: set[str] = set()
+ for what, into in (("jobs", jobs), ("routes", routes)):
+ for rel in profile.files_with(legacy, what):
+ into |= {x.upper() for x in [rel, *used_files(legacy, rel, stems)]}
+ return jobs, routes
+
+
+def runs_as(rules: list[dict[str, Any]], online: set[str], jobs: set[str] | None = None, routes: set[str] | None = None) -> str:
"""How the capability runs in the new application: online (behind screens), as a scheduled job (from JCL), or both;
- a service when the source shows neither."""
+ a service when the source shows neither. For any stack but the mainframe (L1-07, docs/any-legacy.md section 5.4),
+ `jobs` and `routes` are the source files of job definitions and routes, with the files they use: a rule whose code
+ is one of them, or whose entry cites one, runs as a scheduled job, or as a service when no screen reaches it; a
+ library when nothing in the source shows how it runs."""
entries = [e.lower() for r in rules for e in r.get("entry") or []]
on = any("/csd/" in e or e.endswith(".csd") for e in entries) or any(str(r.get("program", "")).upper() in online for r in rules)
job = any(re.search(r"/(jcl|proc|scheduler)/|\.jcl\b|\.prc\b", e) for e in entries)
- return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service"
+ if jobs is None:
+ return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service"
+ code = {str(r.get("program", "")).upper() for r in rules} | {e.rsplit(":", 1)[0].upper() for e in entries}
+ on = on or bool(code & online)
+ job = job or bool(code & jobs)
+ served = bool(code & (routes or set()))
+ return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service" if served else "library"
def screens_for(key: str, codes: set[str], rule_keys: set[str], modern: dict[str, Any], journeys: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
@@ -191,7 +217,8 @@ def questions_for(rule_keys: list[str], rules: dict[str, Any], sme: list[dict[st
return found
-def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None,
+ contracts: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
"""Every capability's specification without the model's parts, and what the model step is to write for each."""
requirements = folder.load("outputs/reconcile/requirements.json") or {}
rules = {r["key"]: r for r in (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or []}
@@ -205,7 +232,15 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None
signed[x["function"]].append({"reviewer": x.get("reviewer", ""), "at": x.get("at", ""), "comment": x.get("comment", "")})
online = {p["name"].upper() for s in inventory.get("screens") or [] for p in s.get("programs") or []} | \
{str(t.get("program", "")).upper() for t in flow.get("transactions") or []}
- uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {}
+ jobs: set[str] | None = None
+ routes: set[str] | None = None
+ if contracts is not None: # any stack but the mainframe (L1-06): the tables and entities each source file names
+ from reframe.design import schema
+ uses = schema.uses(legacy, contracts) if legacy and legacy.is_dir() else {}
+ if legacy and legacy.is_dir():
+ jobs, routes = what_runs(legacy)
+ else:
+ uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {}
domain_of = {f: d for d in requirements.get("domains") or [] for f in d.get("functions") or []}
names = requirements.get("names") or {}
found = []
@@ -234,7 +269,7 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None
"domain_key": domain.get("key", ""), "number": cap["number"], "title": cap.get("title", ""), "story": cap.get("story", ""),
"risk": cap.get("risk", ""), "touches": cap.get("touches") or [],
"status": "final" if signed.get(page) else "draft", "signed_off": signed.get(page) or [],
- "runs_as": runs_as(mine, online),
+ "runs_as": runs_as(mine, online, jobs, routes),
"requirements": [{"key": f"{page}/{q['code']}", "code": q["code"], "kind": q.get("kind", ""), "pattern": q.get("pattern", ""), "text": q["text"],
"rules": q.get("rules") or [], "class": requirement_class([rules[k] for k in q.get("rules") or [] if k in rules])} for q in reqs],
"rules": [{"key": r["key"], "name": r.get("name", ""), "kind": r.get("kind", ""), "class": class_of(r.get("kind", "")),
@@ -397,7 +432,8 @@ def stack_of(folder, stack: str | None) -> dict[str, Any] | None:
return folder.load(STACK) or None
-def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None,
+ screenless: bool = False) -> dict[str, Any]:
"""D6. `more(name, data)` gives a batch's extra input for a round (the decisions that name its capabilities);
`signoffs` adds sign-offs read in the round; `plan_only` says what would be redone, and why, without a step."""
from reframe.claude.steps import stop_for
@@ -407,12 +443,22 @@ def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = F
project = folder.state["project"]
if not (folder.load("outputs/reconcile/requirements.json") or {}).get("functions"):
raise ValueError("run the reconciliation first")
- if not folder.load("design/modern.json"):
+ if not screenless and not folder.load("design/modern.json"): # a codebase with no screens has none to wait for (L1-04)
raise ValueError("run the screen inventory, the flow, the journeys and the modern screens first")
target = stack_of(folder, None if plan_only else stack)
types = data_contracts.stack_types(target)
- built = assemble(folder, places["legacy"], signoffs)
- books = data_contracts.contracts(places["legacy"], set(built["books"]), types)
+ from reframe.source import profile
+ stack_profile = profile.of_run(folder)
+ schema_problems: list[str] = []
+ if stack_profile.get("family", "mainframe") == "mainframe":
+ built = assemble(folder, places["legacy"], signoffs)
+ books = data_contracts.contracts(places["legacy"], set(built["books"]), types)
+ else: # the schema with no model and the entities by a checked step (L1-06)
+ from reframe.design import schema
+ read = schema.read(folder, None if plan_only else claude, places["legacy"], stack_profile, types)
+ schema_problems = [f"data contracts: {p}" for p in read["problems"]]
+ built = assemble(folder, places["legacy"], signoffs, read["contracts"])
+ books = {name: c for name, c in read["contracts"].items() if name in set(built["books"])}
if not plan_only:
folder.save(CONTRACTS, {"stack": target, "notes": types["notes"], "contracts": books})
saved = folder.load(FILE, {}) or {}
@@ -443,7 +489,8 @@ def one(item) -> None:
safe = slug(name)[:50] + "-" + hashlib.sha256(name.encode()).hexdigest()[:6] # unique: batches of one function share a long name
path = folder_in / f"specs-{safe}.json"
path.write_text(json.dumps(data, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
answer, wrong, attempts = None, ["no answer"], 0
for attempt in (1, 2):
attempts = attempt
@@ -491,7 +538,7 @@ def one(item) -> None:
value = {"batches": kept, "log": log, "stack": target, "stack_notes": types["notes"],
"specs": [{k: s[k] for k in ("key", "function", "function_name", "domain", "number", "title", "status", "runs_as")} for s in specs],
"counts": counts(specs, books),
- "problems": batch_problems + found,
+ "problems": batch_problems + schema_problems + found,
"steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)}
folder.save(FILE, value)
value["full"] = specs
@@ -509,7 +556,7 @@ def counts(specs: list[dict[str, Any]], books: dict[str, Any]) -> dict[str, Any]
"contracts": len(books), "tables": sum(len(s["tables"]) for s in specs), "gaps": sum(s["gaps"] for s in specs),
"questions": len({q["id"] or q["question"] for s in specs for q in s["questions"]}),
"classes": {c: sum(1 for s in specs for r in s["rules"] if r["class"] == c) for c in CLASS_ORDER},
- "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service")}}
+ "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service", "library")}}
def main(argv: list[str] | None = None) -> int:
diff --git a/src/reframe/reconcile/audit.py b/src/reframe/reconcile/audit.py
index 3973c381..77736290 100644
--- a/src/reframe/reconcile/audit.py
+++ b/src/reframe/reconcile/audit.py
@@ -205,7 +205,8 @@ def one(number: int, batch: list[dict[str, Any]]) -> None:
step_name = f"audit-{label}-b{number}{'-retry' if attempt == 2 else ''}"
path = work / f"{step_name}.json"
path.write_text(json.dumps({"items": [shown(i, i["id"] in with_note) for i in pending.values()]}, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
if attempt == 2:
prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items()))
step = claude.run(step_name, prompt, timeout=3600, schema=SCHEMA)
diff --git a/src/reframe/reconcile/decide.py b/src/reframe/reconcile/decide.py
index 0b347869..8ad8db37 100644
--- a/src/reframe/reconcile/decide.py
+++ b/src/reframe/reconcile/decide.py
@@ -211,7 +211,8 @@ def _prompt(self, path: Path) -> str:
+ ("; " if documents and answers else "")
+ (f"answered SME questions in analysis/{project}/reframe/reconcile/{self.name}-answers.json" if answers else "") + ".")
from reframe.reconcile.units import one_tool
- return one_tool(self.folder, PROMPT.format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}",
+ from reframe.source import profile
+ return one_tool(self.folder, profile.in_words(PROMPT, profile.of_run(self.folder)).format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}",
legacy=f"legacy/{project}", context=context, kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE), ONE_TOOL)
def answers(self) -> list[dict[str, Any]]:
diff --git a/src/reframe/reconcile/describe.py b/src/reframe/reconcile/describe.py
index 5e31e46d..89ae5db9 100644
--- a/src/reframe/reconcile/describe.py
+++ b/src/reframe/reconcile/describe.py
@@ -122,7 +122,8 @@ def one(b: dict[str, Any]) -> None:
path = folder_in / f"{name}{'-retry' if attempt == 2 else ''}.json"
path.write_text(json.dumps({"rules": [{"key": i["key"], "program": i["program"], "name": i["name"], "text": i["text"], "cites": i["cites"]}
for i in todo.values()]}, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE)
if attempt == 2:
prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items()))
diff --git a/src/reframe/reconcile/expert.py b/src/reframe/reconcile/expert.py
index 2790ec9c..d8f9c0b0 100644
--- a/src/reframe/reconcile/expert.py
+++ b/src/reframe/reconcile/expert.py
@@ -77,7 +77,7 @@ def blind(item: dict[str, Any], with_note: bool) -> dict[str, Any]:
"defect_note": item["defect_note"] if with_note else ""}
-def page(rows: list[dict[str, Any]], project: str, origin: str) -> str:
+def page(rows: list[dict[str, Any]], project: str, origin: str, guide_text: str = GUIDE) -> str:
def code(ex: dict[str, Any]) -> str:
if ex["missing"]:
return f"