From 75d5cb3465796cf630f6858c69e8ce0b6449bd6b Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 07:59:47 -0700
Subject: [PATCH 1/8] L1-01: the stack profile
After the snapshot, with no model, Reframe works out what the codebase
is and records it in stack-profile.json (docs/any-legacy.md, section 4):
- languages, counted by file and by line: by extension, by content for
the shared `.inc`, `.h` and `.prc`, and a mainframe member with no
extension as reframe.source.kinds classes it;
- the family that carries more than half the lines (mainframe, java,
dotnet, web-script, front-end, native, 4gl, or mixed). SQL counts
toward none, since every stack has a schema. JavaScript and TypeScript
count toward front-end only when no other family has a quarter of the
code. Libraries kept in the tree (node_modules, vendor, packages,
minified files) are not counted;
- what it has, each with the files that show it: user interface, routes,
jobs and data;
- the prompts' words: "COBOL" for the mainframe, as today, or the
family's two main languages ("Java and JSP").
`reframe run --legacy ` overrides the family, and the profile
records what was found and what it was told. For a local source, the
guided run shows the profile before the run starts and asks only when
no family carries most of the code. `reframe status` shows it, and both
business reviews show it at the foot of the overview. The package check
is now shown only for mainframe code, the only code AWS Transform reads.
Tests: six synthetic fixtures written for the tests (a Java web
application, .NET, PHP, a batch-only Java job, a mainframe and a mixed
codebase) in tests/stacks.py. Each one's family, what it has with the
files, the words, the skipped libraries, the shared extensions, the
override, the snapshot's record, status and the reports.
Bank-of-Z profiles as mainframe: COBOL carries 33.8k lines against
about 3.8k of Java and JavaScript.
Prepared with AI assistance.
---
docs/cli.md | 1 +
src/reframe/core/cli.py | 4 +
src/reframe/core/commands/reading.py | 7 +-
src/reframe/core/commands/starting.py | 15 +-
src/reframe/core/guide.py | 25 ++-
src/reframe/report/build.py | 18 +-
src/reframe/report/template.html | 1 +
src/reframe/source/profile.py | 206 +++++++++++++++++
src/reframe/source/snapshot.py | 7 +-
tests/source/test_profile.py | 120 ++++++++++
tests/stacks.py | 309 ++++++++++++++++++++++++++
11 files changed, 697 insertions(+), 16 deletions(-)
create mode 100644 src/reframe/source/profile.py
create mode 100644 tests/source/test_profile.py
create mode 100644 tests/stacks.py
diff --git a/docs/cli.md b/docs/cli.md
index bdde6f59..89dab517 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -108,6 +108,7 @@ Assess mainframe source with AWS Transform and Claude, or with Claude only (--to
| `--terraform ` | the Terraform binary to use (default: REFRAME_TERRAFORM, then the one Reframe installed, then terraform on PATH) |
| `--foreground` | run in this terminal instead of a background worker |
| `--tools both\|claude\|aws` | both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: AWS Transform only (reframe claude adds Claude later) |
+| `--legacy mainframe\|java\|dotnet\|web-script\|front-end\|native\|4gl\|mixed` | the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, section 4); AWS Transform is offered only for mainframe |
| `--max-agents ` | the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo) |
| `--auth subscription\|api-key\|bedrock` | how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock (with --tools claude, --profile and --region are used for Bedrock only) |
diff --git a/src/reframe/core/cli.py b/src/reframe/core/cli.py
index afb4ba68..fac2d2a0 100644
--- a/src/reframe/core/cli.py
+++ b/src/reframe/core/cli.py
@@ -11,6 +11,7 @@
import sys
from reframe import __version__
+from reframe.source.profile import FAMILIES
# how Claude signs in; the same as reframe.claude.preflight.AUTHS, kept here so the CLI starts without loading it
AUTHS = ("subscription", "api-key", "bedrock")
@@ -66,6 +67,9 @@ def command(name: str, help: str) -> argparse.ArgumentParser:
run.add_argument("--tools", choices=("both", "claude", "aws"), default="both",
help="both: AWS Transform and Claude, side by side (needs an AWS account); claude: Claude only, with no AWS at all; aws: "
"AWS Transform only (reframe claude adds Claude later)")
+ run.add_argument("--legacy", choices=FAMILIES, default=None,
+ help="the codebase's family, overriding the stack profile Reframe works out after the snapshot (docs/any-legacy.md, "
+ "section 4); AWS Transform is offered only for mainframe")
run.add_argument("--max-agents", type=int, help="the agent limit for Claude's rule extraction (default 600; use 650 or more for CardDemo)")
run.add_argument("--auth", choices=AUTHS, default=None,
help="how Claude signs in: your Claude subscription (default), an Anthropic API key in ANTHROPIC_API_KEY, or Amazon Bedrock "
diff --git a/src/reframe/core/commands/reading.py b/src/reframe/core/commands/reading.py
index a75e9336..368e4772 100644
--- a/src/reframe/core/commands/reading.py
+++ b/src/reframe/core/commands/reading.py
@@ -37,9 +37,12 @@ def status(args) -> int:
ui.hint(f"{state.get('source')} · {state.get('mode')} mode" + (" · Claude only, no AWS" if alone else "")
+ (f" · worker running (process {pid})" if pid else ""))
ui.state("Status", f"{state.get('status')} · stage {state.get('stage')}", STATUS_STYLE.get(str(state.get("status")), "bold yellow"))
- from reframe.source import package_check
+ from reframe.source import package_check, profile
+ stack = folder.load(profile.FILE)
+ if stack:
+ ui.state("Stack", profile.summary(stack), "")
checked = folder.load(package_check.FILE)
- if checked:
+ if checked and (not stack or stack.get("family") == "mainframe"): # what AWS Transform makes of it: mainframe code only
ui.state("Package check", package_check.summary(checked), "")
for note in checked.get("notes", [])[1:]:
ui.hint(note)
diff --git a/src/reframe/core/commands/starting.py b/src/reframe/core/commands/starting.py
index ef8b90e5..f21c62cc 100644
--- a/src/reframe/core/commands/starting.py
+++ b/src/reframe/core/commands/starting.py
@@ -20,7 +20,8 @@ def run(args) -> int:
if getattr(args, "tools", "both") == "claude":
return commands.start_claude_only(source=args.source, ref=args.ref, mode=args.mode, project=args.project, foreground=args.foreground,
max_agents=getattr(args, "max_agents", None), auth=auth,
- profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None)
+ profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None,
+ legacy=getattr(args, "legacy", None))
from reframe.core.setup import load_config
saved = load_config()
profile = args.profile or saved.get("profile")
@@ -29,11 +30,11 @@ def run(args) -> int:
both = getattr(args, "tools", "both") == "both" # the Claude assessment alongside, as the guided run offers by default
return commands.start(source=args.source, profile=profile, ref=args.ref, mode=args.mode, region=args.region or saved.get("region") or "us-east-1",
project=args.project, graph=args.graph, terraform=args.terraform, foreground=args.foreground,
- claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None)
+ claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=getattr(args, "legacy", None))
def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, project: str | None, graph: str | None,
- terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None) -> int:
+ terraform: str | None, foreground: bool, claude: dict[str, Any] | None = None, legacy: str | None = None) -> int:
"""Stage 0 and the Neptune choice here, then stages 1 to 8 in a background worker (or this terminal)."""
from reframe.core import pipeline, ui
from reframe.source.snapshot import kind
@@ -45,7 +46,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str,
except (Stop, ReframeError) as error:
return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error)))
folder.update(project=project, source=source, ref=ref, mode=mode, graph_arg=graph, profile=profile,
- region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING")
+ region=region, terraform=pipeline.terraform_binary(terraform), started_at=iso(), stage="preflight", status="RUNNING",
+ **({"legacy": legacy} if legacy else {}))
ui.section(f"Run {folder.root.name}")
ui.hint(f"{project} · {mode} mode · run folder {folder.root}")
ctx = pipeline.Context.load(folder)
@@ -75,7 +77,8 @@ def start(*, source: str, profile: str, ref: str | None, mode: str, region: str,
def start_claude_only(*, source: str, ref: str | None, mode: str, project: str | None, foreground: bool,
- max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None) -> int:
+ max_agents: int | None = None, auth: str = "subscription", profile: str | None = None, region: str | None = None,
+ legacy: str | None = None) -> int:
"""A Claude-only run (docs/release-1.md, section 2): the snapshot and the Claude assessment, in one commands.worker, with no AWS resources.
With Amazon Bedrock, the AWS profile (or a Bedrock API key) is used to sign Claude in, and for nothing else."""
from reframe.claude import pipeline as claude_pipeline
@@ -89,7 +92,7 @@ def start_claude_only(*, source: str, ref: str | None, mode: str, project: str |
except (Stop, ReframeError) as error:
return commands._fail(error if isinstance(error, Stop) else Stop(Outcome.REFUSED, str(error)))
folder.update(tools="claude", project=project, source=source, ref=ref, mode=mode, started_at=iso(), stage="snapshot", status="RUNNING",
- **({"profile": profile, "region": region or "us-east-1"} if profile else {}))
+ **({"profile": profile, "region": region or "us-east-1"} if profile else {}), **({"legacy": legacy} if legacy else {}))
claude_pipeline.request(pipeline.Context.load(folder), auth=auth, max_agents=max_agents, mode=mode)
ui.section(f"Run {folder.root.name} · Claude only")
signin = {"subscription": "your Claude subscription", "api-key": "your Anthropic API key",
diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py
index 0df87742..b7b979c8 100644
--- a/src/reframe/core/guide.py
+++ b/src/reframe/core/guide.py
@@ -211,6 +211,24 @@ def check_url(value: str) -> str | None:
return str(Path(archive).expanduser().resolve()), None
+def stack(chosen_source: str) -> str | None:
+ """The stack profile of a local source (L1-01), shown before the run starts; asked only when no family carries most of
+ the code. Returns the family the person chose, or None to keep what was found. A Git URL is profiled after the snapshot."""
+ from reframe.source import profile
+ path = Path(chosen_source)
+ if not path.exists():
+ ui.hint("The stack profile is worked out after the snapshot; reframe status shows it.")
+ return None
+ with ui.console.status("Working out the stack…"):
+ found = profile.profile_folder(path) if path.is_dir() else profile.profile_archive(path)
+ ui.state("Stack", profile.summary(found), "")
+ if found["found"] != "mixed":
+ return None
+ families = list(profile.FAMILIES)
+ picked = ui.choose("No family carries most of the code. Which is it?", [(f, "") for f in families], len(families))
+ return None if families[picked - 1] == "mixed" else families[picked - 1]
+
+
# ---- 4 and 5. choices, summary, start ----------------------------------------------------------------
@@ -355,13 +373,14 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
+ legacy = stack(chosen)
picked = claude_only_choices(chosen)
if not claude_only_summary(chosen, ref, picked):
ui.hint("Nothing was started or created.")
return 0
return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"],
foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"],
- auth=picked["claude"]["auth"])
+ auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {}))
if not prerequisites(m):
return 1
sign = sign_in()
@@ -371,6 +390,7 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
+ legacy = stack(chosen)
picked = choices(chosen)
if not summary(chosen, ref, sign, picked):
ui.hint("Nothing was started or created.")
@@ -380,7 +400,8 @@ def run(args) -> int:
ui.hint("Stopped. Nothing was started or created.")
return 130
return commands.start(source=chosen, profile=sign.profile, ref=ref, mode=picked["mode"], region=sign.region, project=picked["project"],
- graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude"))
+ graph=picked["graph"], terraform=None, foreground=bool(getattr(args, "foreground", False)), claude=picked.get("claude"),
+ **({"legacy": legacy} if legacy else {}))
def setup_only(args) -> int:
diff --git a/src/reframe/report/build.py b/src/reframe/report/build.py
index b3111232..e78f025b 100644
--- a/src/reframe/report/build.py
+++ b/src/reframe/report/build.py
@@ -28,11 +28,19 @@
# ---- reading AWS's files -------------------------------------------------------------------------
+def _stack(folder: RunFolder) -> str:
+ """The stack profile's line (L1-01), for the source line at the foot of the overview."""
+ from reframe.source import profile
+ return profile.summary(folder.load(profile.FILE))
+
+
def _package(folder: RunFolder) -> dict[str, Any]:
"""The package check's line and notes (MP-03), for the source line at the foot of the overview."""
- from reframe.source import package_check
- checked = folder.load(package_check.FILE)
- return {"summary": package_check.summary(checked), "notes": checked.get("notes", [])[1:]} if checked else {}
+ from reframe.source import package_check, profile
+ checked, stack = folder.load(package_check.FILE), folder.load(profile.FILE)
+ if not checked or (stack and stack.get("family") != "mainframe"): # what AWS Transform makes of it: mainframe code only
+ return {}
+ return {"summary": package_check.summary(checked), "notes": checked.get("notes", [])[1:]}
def _yaml(path: Path) -> Any:
@@ -157,7 +165,7 @@ def collect(folder: RunFolder) -> dict[str, Any]:
"project": state.get("project"),
"source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"),
"sha256": snapshot.get("sha256"), "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"),
- "package": _package(folder)},
+ "package": _package(folder), "stack": _stack(folder)},
"started_at": state.get("started_at"), "retrieved_at": state.get("retrieved_at"),
"graph": (state.get("graph") or {}).get("kind"),
"domains": ranked, "functions": functions, "capabilities": capabilities,
@@ -387,7 +395,7 @@ def collect_claude(folder: RunFolder) -> dict[str, Any]:
return {
"generated_at": iso(), "run": folder.root.name, "project": project, "tool": CLAUDE,
"source": {"form": snapshot.get("form"), "commit": snapshot.get("commit"), "files": snapshot.get("files"), "sha256": snapshot.get("sha256"),
- "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), "package": _package(folder)},
+ "name": Path(str(snapshot.get("source") or "")).name or snapshot.get("source"), "package": _package(folder), "stack": _stack(folder)},
"started_at": (folder.state.get("claude") or {}).get("started_at"), "retrieved_at": model.get("read_at"),
"domains": domains, "functions": functions, "capabilities": capabilities, "requirements": requirements, "rules": rules, "questions": questions,
"data_model": data_objects, "sections": sections, "classification": [], "unclassified": [], "issues": [], "decisions": decisions,
diff --git a/src/reframe/report/template.html b/src/reframe/report/template.html
index eded368b..fb071504 100644
--- a/src/reframe/report/template.html
+++ b/src/reframe/report/template.html
@@ -266,6 +266,7 @@
+
+
+""",
+ "orders.php": """ 100) {
+ $total = $total * 0.90;
+}
+save_order($_POST['customer'], $quantity, $total);
+header('Location: index.php');
+""",
+ "includes/db.inc": """prepare('INSERT INTO orders (customer, quantity, total) VALUES (?, ?, ?)')->execute([$customer, $quantity, $total]);
+}
+""",
+ "schema.sql": "CREATE TABLE orders (\n id INTEGER PRIMARY KEY,\n customer VARCHAR(40) NOT NULL,\n quantity INT,\n total DECIMAL(10,2)\n);\n",
+}
+
+BATCH = {
+ "src/main/java/org/demo/billing/BillingJobConfig.java": """package org.demo.billing;
+
+import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@EnableBatchProcessing
+public class BillingJobConfig {
+ public static final String JOB = "monthlyBilling";
+}
+""",
+ "src/main/java/org/demo/billing/InvoiceProcessor.java": """package org.demo.billing;
+
+import java.math.BigDecimal;
+
+public class InvoiceProcessor {
+ static final BigDecimal LATE_FEE = new BigDecimal("15.00");
+
+ public BigDecimal amountDue(BigDecimal balance, int daysLate) {
+ if (balance.signum() <= 0) {
+ return BigDecimal.ZERO;
+ }
+ return daysLate > 30 ? balance.add(LATE_FEE) : balance;
+ }
+}
+""",
+ "src/main/resources/schema.sql": "CREATE TABLE INVOICE (\n ID BIGINT PRIMARY KEY,\n BALANCE DECIMAL(12,2) NOT NULL,\n DUE_DATE DATE\n);\n",
+ "deploy/crontab": "0 1 1 * * /opt/billing/run-job.sh monthlyBilling\n",
+}
+
+MAINFRAME = {"app/bms/SIGN00.bms": bms("SIGN00", "SIGN0A", "ENTER=Sign-on F3=Exit"), "app/bms/MENU00.bms": bms("MENU00", "MENU0A", "ENTER=Go F3=Exit"),
+ "app/cpy/MENU02Y.cpy": MENU_TABLE, "app/cbl/SIGN00C.cbl": SIGNON, "app/cbl/MENU00C.cbl": MENU, "app/csd/DEMO.csd": CSD}
+
+MIXED = {**{f"java/{k}": v for k, v in JAVA_WEB.items() if k.endswith(".java")}, **{f"dotnet/{k}": v for k, v in DOTNET.items() if k.endswith(".cs")},
+ **{f"php/{k}": v for k, v in PHP.items() if k.endswith(".php")}}
+"""Java, C# and PHP, none with more than half the lines."""
+
+FIXTURES = {"java": JAVA_WEB, "dotnet": DOTNET, "web-script": PHP, "batch": BATCH, "mainframe": MAINFRAME, "mixed": MIXED}
+
+
+def write(root: Path, files: dict[str, str]) -> Path:
+ for name, text in files.items():
+ (root / name).parent.mkdir(parents=True, exist_ok=True)
+ (root / name).write_text(text)
+ return root
From ec180ab413ecd02f084da30db76aabed69b93ef5 Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 08:03:01 -0700
Subject: [PATCH 2/8] L1-02: pipelines 1 and 2 by profile
Pipeline 1 (docs/any-legacy.md, section 5.1): AWS Transform writes
requirements and business rules only for mainframe code, so it is
offered only when the stack profile's family is mainframe.
- `reframe run --legacy ` other than mainframe, with --tools
both or aws, is refused at once with the Claude-only command.
- Otherwise the check is at the end of stage 1: after the snapshot has
been profiled and before stage 2 makes the first AWS resource. Nothing
is created in AWS, and the message gives the Claude-only command. A
run from before the profile goes on as a mainframe run.
- The guided run does not offer AWS Transform for a local source that
is not mainframe code: it says so and goes on as Claude only.
Pipeline 2 (section 5.2): a program's name follows the profile. For the
mainframe it is still the member name, the file's stem in capitals. For
any other family it is the file's path within the source, so two
OrderService.java files in different folders stay apart. A rule card
joins its module of the plugin's map by the module's name or by its
file, in the card's domain, Claude's requirements, its business review
and its graph. The plugin's commands, the estimate and the agent limit
are unchanged.
Tests: the refusal and its place in stage order, mainframe and older
runs going on, --legacy with AWS, the guided run on a PHP source,
program names by family, and two files of one name kept apart.
Prepared with AI assistance.
---
src/reframe/claude/graph.py | 3 +-
src/reframe/claude/requirements.py | 3 +-
src/reframe/claude/retrieve.py | 38 +++++++--
src/reframe/core/commands/starting.py | 6 +-
src/reframe/core/guide.py | 25 ++++--
src/reframe/core/pipeline.py | 15 ++++
src/reframe/report/build.py | 3 +-
tests/core/test_by_profile.py | 117 ++++++++++++++++++++++++++
8 files changed, 192 insertions(+), 18 deletions(-)
create mode 100644 tests/core/test_by_profile.py
diff --git a/src/reframe/claude/graph.py b/src/reframe/claude/graph.py
index 1ff1509c..a5159a6b 100644
--- a/src/reframe/claude/graph.py
+++ b/src/reframe/claude/graph.py
@@ -114,7 +114,8 @@ def build(run: str, sha256: str, model: dict[str, Any], generated: dict[str, Any
for ident in step.get("nodes") or []:
if ident in node_iri:
q.add(s, "involves", node_iri[ident], literal=False)
- modules_by_name = {m.get("name", "").upper(): node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri}
+ from reframe.claude.retrieve import module_keys
+ modules_by_name = {key: node_iri[m["id"]] for m in model.get("modules") or [] if m.get("id") in node_iri for key in module_keys(m)}
rule_iri = {}
for card in model.get("rules") or []:
r = q.iri("rule", card["id"])
diff --git a/src/reframe/claude/requirements.py b/src/reframe/claude/requirements.py
index 3163f196..521e9a1a 100644
--- a/src/reframe/claude/requirements.py
+++ b/src/reframe/claude/requirements.py
@@ -61,7 +61,8 @@
def domain_input(model: dict[str, Any], domain: dict[str, Any]) -> dict[str, Any]:
modules = [m for m in model.get("modules") or [] if m.get("domain") == domain["id"]]
- names = {m.get("name", "").upper() for m in modules}
+ from reframe.claude.retrieve import module_keys
+ names = {key for m in modules for key in module_keys(m)}
members = set(domain.get("members") or [])
rules = [r for r in model.get("rules") or [] if r.get("domain") == domain["id"] or r.get("program", "").upper() in names]
rule_ids = {r["id"] for r in rules}
diff --git a/src/reframe/claude/retrieve.py b/src/reframe/claude/retrieve.py
index 04707040..494340cd 100644
--- a/src/reframe/claude/retrieve.py
+++ b/src/reframe/claude/retrieve.py
@@ -37,13 +37,37 @@ def sections(markdown: str, level: int = 2) -> list[dict[str, str]]:
return out
-def program_of(path: str) -> str:
- """The program name a source path stands for: the file's stem, upper-cased (COBOL member names)."""
+def program_of(path: str, family: str = "mainframe") -> str:
+ """The program name a source path stands for (docs/any-legacy.md, section 5.2). For the mainframe, the file's stem,
+ upper-cased, as COBOL members are named. For any other family, the file's path within the source, so two files of the
+ same name in different folders stay apart."""
+ if family != "mainframe":
+ return path_key(path)
stem = Path(path).name.split(".")[0]
return stem.upper()
-def parse_rules(markdown: str) -> list[dict[str, Any]]:
+def path_key(path: str) -> str:
+ """A source path as Reframe compares it: forward slashes, no leading `./` or `/`."""
+ return path.replace("\\", "/").lstrip("/").removeprefix("./")
+
+
+def module_keys(module: dict[str, Any]) -> set[str]:
+ """What a rule card's program may name a module of the plugin's map by, upper-cased: the module's name (a mainframe
+ member's), and its file's path (any other family's program name)."""
+ keys = {str(module.get("name") or "").upper()} - {""}
+ if module.get("file"):
+ keys.add(path_key(str(module["file"])).upper())
+ return keys
+
+
+def family(folder: RunFolder) -> str:
+ """The run's family from its stack profile (L1-01); a run from before the profile is a mainframe run."""
+ from reframe.source import profile
+ return str((folder.load(profile.FILE) or {}).get("family") or "mainframe")
+
+
+def parse_rules(markdown: str, family: str = "mainframe") -> list[dict[str, Any]]:
cards = []
matches = list(RULE.finditer(markdown))
for i, match in enumerate(matches):
@@ -74,7 +98,7 @@ def parse_rules(markdown: str) -> list[dict[str, Any]]:
"id": match.group(1), "name": match.group(2).strip(), "category": fields.get("category", ""),
"priority": fields.get("priority", "").split(" ")[0], "source": source.strip("` "), "path": path,
"line": int(where.group(2)) if where else None, "line_end": int(where.group(3)) if where and where.group(3) else None,
- "program": program_of(path) if path else "", "plain": fields.get("plain english", ""),
+ "program": program_of(path, family) if path else "", "plain": fields.get("plain english", ""),
"spec": [{"clause": c, "text": t} for c, t in spec], "parameters": fields.get("parameters", ""),
"edge_cases": fields.get("edge cases handled", ""), "defect": fields.get("suspected defect", ""),
"confidence": level, "confidence_note": confidence[len(level):].strip(" —-") if confidence else ""})
@@ -146,10 +170,10 @@ def text(name: str) -> str:
if topology.get("root"):
walk(topology["root"], None, parts)
rules_md = text("BUSINESS_RULES.md")
- cards = parse_rules(rules_md)
- module_domain = {m["name"].upper(): m["domain"] for m in parts["modules"] if m.get("name")}
+ cards = parse_rules(rules_md, family(folder))
+ module_domain = {key: m["domain"] for m in parts["modules"] for key in module_keys(m)}
for card in cards:
- card["domain"] = module_domain.get(card["program"], "")
+ card["domain"] = module_domain.get(card["program"].upper(), "")
result = json.loads(text("rules_result.json") or "{}") if (analysis / "rules_result.json").exists() else {}
stats = result.get("stats") if isinstance(result, dict) else None
return {
diff --git a/src/reframe/core/commands/starting.py b/src/reframe/core/commands/starting.py
index f21c62cc..64232c0d 100644
--- a/src/reframe/core/commands/starting.py
+++ b/src/reframe/core/commands/starting.py
@@ -22,6 +22,10 @@ def run(args) -> int:
max_agents=getattr(args, "max_agents", None), auth=auth,
profile=args.profile if auth == "bedrock" else None, region=args.region if auth == "bedrock" else None,
legacy=getattr(args, "legacy", None))
+ legacy = getattr(args, "legacy", None)
+ if legacy and legacy != "mainframe": # AWS Transform is offered only for the mainframe (docs/any-legacy.md, section 5.1)
+ return commands._fail(Stop(Outcome.REFUSED, f"--legacy {legacy}: AWS Transform writes requirements only for mainframe code, so "
+ f"this run is Claude only: reframe run --tools claude --legacy {legacy} --source {args.source}"))
from reframe.core.setup import load_config
saved = load_config()
profile = args.profile or saved.get("profile")
@@ -30,7 +34,7 @@ def run(args) -> int:
both = getattr(args, "tools", "both") == "both" # the Claude assessment alongside, as the guided run offers by default
return commands.start(source=args.source, profile=profile, ref=args.ref, mode=args.mode, region=args.region or saved.get("region") or "us-east-1",
project=args.project, graph=args.graph, terraform=args.terraform, foreground=args.foreground,
- claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=getattr(args, "legacy", None))
+ claude={"auth": auth, "max_agents": getattr(args, "max_agents", None)} if both else None, legacy=legacy)
def start(*, source: str, profile: str, ref: str | None, mode: str, region: str, project: str | None, graph: str | None,
diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py
index b7b979c8..db18d625 100644
--- a/src/reframe/core/guide.py
+++ b/src/reframe/core/guide.py
@@ -211,22 +211,24 @@ def check_url(value: str) -> str | None:
return str(Path(archive).expanduser().resolve()), None
-def stack(chosen_source: str) -> str | None:
+def stack(chosen_source: str) -> tuple[str | None, str | None]:
"""The stack profile of a local source (L1-01), shown before the run starts; asked only when no family carries most of
- the code. Returns the family the person chose, or None to keep what was found. A Git URL is profiled after the snapshot."""
+ the code. Returns the family (None when it is not known yet) and what the person chose (None to keep what was found).
+ A Git URL is profiled after the snapshot."""
from reframe.source import profile
path = Path(chosen_source)
if not path.exists():
ui.hint("The stack profile is worked out after the snapshot; reframe status shows it.")
- return None
+ return None, None
with ui.console.status("Working out the stack…"):
found = profile.profile_folder(path) if path.is_dir() else profile.profile_archive(path)
ui.state("Stack", profile.summary(found), "")
if found["found"] != "mixed":
- return None
+ return found["found"], None
families = list(profile.FAMILIES)
picked = ui.choose("No family carries most of the code. Which is it?", [(f, "") for f in families], len(families))
- return None if families[picked - 1] == "mixed" else families[picked - 1]
+ told = families[picked - 1]
+ return told, None if told == "mixed" else told
# ---- 4 and 5. choices, summary, start ----------------------------------------------------------------
@@ -373,7 +375,7 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
- legacy = stack(chosen)
+ _, legacy = stack(chosen)
picked = claude_only_choices(chosen)
if not claude_only_summary(chosen, ref, picked):
ui.hint("Nothing was started or created.")
@@ -390,7 +392,16 @@ def run(args) -> int:
if picked_source is None:
return 1
chosen, ref = picked_source
- legacy = stack(chosen)
+ family, legacy = stack(chosen)
+ if family and family != "mainframe": # AWS Transform is not offered (docs/any-legacy.md, section 5.1)
+ ui.warn("AWS Transform writes requirements only for mainframe code, so this run is Claude only, with no AWS.")
+ picked = claude_only_choices(chosen)
+ if not claude_only_summary(chosen, ref, picked):
+ ui.hint("Nothing was started or created.")
+ return 0
+ return commands.start_claude_only(source=chosen, ref=ref, mode=picked["mode"], project=picked["project"],
+ foreground=bool(getattr(args, "foreground", False)), max_agents=picked["claude"]["max_agents"],
+ auth=picked["claude"]["auth"], **({"legacy": legacy} if legacy else {}))
picked = choices(chosen)
if not summary(chosen, ref, sign, picked):
ui.hint("Nothing was started or created.")
diff --git a/src/reframe/core/pipeline.py b/src/reframe/core/pipeline.py
index 282821c0..78a00d0f 100644
--- a/src/reframe/core/pipeline.py
+++ b/src/reframe/core/pipeline.py
@@ -99,6 +99,20 @@ def prepare(ctx: Context, prompt: Callable[[str], str] | None, say: Callable[[st
# ---- the worker ----------------------------------------------------------------------------------
+NOT_MAINFRAME = ("AWS Transform writes requirements and business rules only for mainframe code (docs/any-legacy.md, section 5.1), "
+ "and this codebase's stack profile is {family}: {summary}. Nothing was created in AWS. Assess it with Claude only: "
+ "reframe run --tools claude --source {source}")
+
+
+def refuse_unless_mainframe(folder: RunFolder) -> None:
+ """Stage 1's end: pipeline 1 goes on only for a mainframe codebase, before anything is made in AWS (L1-02)."""
+ from reframe.source import profile
+ stack = folder.load(profile.FILE)
+ if stack and stack.get("family") != "mainframe":
+ raise Stop(Outcome.REFUSED, NOT_MAINFRAME.format(family=stack["family"], summary=profile.summary(stack),
+ source=folder.state.get("source", "")))
+
+
def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome:
"""Stages 1 to 8. Returns DONE, or raises Stop with the outcome to record. on_resources runs once the run's AWS
resources exist (pipeline 2 starts there, alongside this pipeline)."""
@@ -108,6 +122,7 @@ def work(ctx: Context, on_resources: Callable[[], Any] | None = None) -> Outcome
names = ctx.names()
ctx.stage("snapshot")
record = snapshot.take(ctx.folder, state["source"], state.get("ref"))
+ refuse_unless_mainframe(ctx.folder)
ctx.stage("infrastructure")
tf = ctx.terraform()
diff --git a/src/reframe/report/build.py b/src/reframe/report/build.py
index e78f025b..22659bd6 100644
--- a/src/reframe/report/build.py
+++ b/src/reframe/report/build.py
@@ -334,7 +334,8 @@ def collect_claude(folder: RunFolder) -> dict[str, Any]:
entry["capabilities"].append(cap["id"])
functions.append(entry)
domain["functions"].append(fid)
- names = {m.get("name", "").upper() for m in modules}
+ from reframe.claude.retrieve import module_keys
+ names = {key for m in modules for key in module_keys(m)}
uncited = [c["id"] for c in model.get("rules") or [] if (c.get("domain") == pdomain.get("id") or c.get("program", "").upper() in names)
and c["id"] not in cited_here and c["id"] not in rule_function]
open_qs = [q for q in model.get("sme_questions") or [] if q.get("rule") in cards and q["rule"] not in carried
diff --git a/tests/core/test_by_profile.py b/tests/core/test_by_profile.py
new file mode 100644
index 00000000..791e1b6b
--- /dev/null
+++ b/tests/core/test_by_profile.py
@@ -0,0 +1,117 @@
+"""L1-02: pipelines 1 and 2 by the stack profile (docs/any-legacy.md, sections 5.1 and 5.2). AWS Transform is offered only
+for mainframe code and refused before anything is made otherwise; program names follow the profile."""
+import contextlib
+import io
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from reframe.claude import requirements, retrieve
+from reframe.core import cli, commands, guide, pipeline, setup
+from reframe.core.errors import EXIT_CODES, Outcome, Stop
+from reframe.core.runfolder import RunFolder
+from reframe.source import profile
+from tests import stacks
+from tests.core.test_setup import MAC
+
+JAVA_RULE = """# Business rules: shop
+
+## Orders
+
+### RULE-001: An order over 100 is discounted
+**Category:** Calculation
+**Priority:** P1
+**Source:** `src/main/java/org/demo/shop/service/OrderService.java:13-15`
+**Plain English:** Orders over 100 get ten percent off.
+**Confidence:** High
+
+### RULE-002: Same name, another folder
+**Category:** Validation
+**Priority:** P2
+**Source:** `src/main/java/org/demo/admin/OrderService.java:4`
+**Confidence:** High
+"""
+
+
+class Pipeline1Test(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.folder = RunFolder(Path(self.tmp.name) / "run")
+ self.folder.update(source="/src/shop", project="shop", mode="autonomous", status="RUNNING", stage="snapshot")
+
+ def profiled(self, name):
+ root = stacks.write(Path(self.tmp.name) / name, stacks.FIXTURES[name])
+ self.folder.save(profile.FILE, profile.profile_folder(root))
+
+ def test_refused_after_the_snapshot_before_anything_is_made(self):
+ self.profiled("java")
+ with self.assertRaises(Stop) as stop:
+ pipeline.refuse_unless_mainframe(self.folder)
+ self.assertEqual(stop.exception.outcome.value, "REFUSED")
+ self.assertIn("this codebase's stack profile is java", stop.exception.message)
+ self.assertIn("Nothing was created in AWS", stop.exception.message)
+ self.assertIn("reframe run --tools claude --source /src/shop", stop.exception.message)
+
+ def test_the_stage_order(self):
+ """Stage 1 ends with the check, and stage 2 makes the first AWS resource: nothing is made before the refusal."""
+ import inspect
+ work = inspect.getsource(pipeline.work)
+ self.assertLess(work.index("snapshot.take"), work.index("refuse_unless_mainframe"))
+ self.assertLess(work.index("refuse_unless_mainframe"), work.index('ctx.stage("infrastructure")'))
+
+ def test_mainframe_and_runs_from_before_the_profile_go_on(self):
+ pipeline.refuse_unless_mainframe(self.folder) # no profile: a run from before release 1.1
+ self.profiled("mainframe")
+ pipeline.refuse_unless_mainframe(self.folder)
+
+ def test_legacy_other_than_mainframe_with_aws_is_refused_at_once(self):
+ for tools in ("both", "aws"):
+ args = cli.parser().parse_args(["run", "--source", "/src/shop", "--tools", tools, "--legacy", "dotnet"])
+ with mock.patch.object(commands, "start") as start, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ self.assertEqual(commands.run(args), EXIT_CODES[Outcome.REFUSED])
+ start.assert_not_called()
+ args = cli.parser().parse_args(["run", "--source", "/src/shop", "--tools", "both", "--legacy", "mainframe", "--profile", "p"])
+ with mock.patch.object(commands, "start", return_value=0) as start:
+ commands.run(args)
+ self.assertEqual(start.call_args.kwargs["legacy"], "mainframe")
+
+ def test_the_guided_run_does_not_offer_aws_transform(self):
+ source = str(stacks.write(Path(self.tmp.name) / "web", stacks.PHP))
+ picked = {"mode": "autonomous", "project": "web", "claude": {"auth": "subscription", "max_agents": 600}}
+ with mock.patch("reframe.core.ui.interactive", return_value=True), mock.patch.object(setup, "machine", return_value=MAC), \
+ mock.patch.object(guide, "which_tools", return_value="both"), mock.patch.object(guide, "prerequisites", return_value=True), \
+ mock.patch.object(guide, "sign_in", return_value=type("S", (), {"profile": "p", "region": "r"})()), \
+ mock.patch.object(guide, "source", return_value=(source, None)), mock.patch.object(guide, "choices") as aws_choices, \
+ mock.patch.object(guide, "claude_only_choices", return_value=picked), mock.patch.object(guide, "claude_only_summary", return_value=True), \
+ mock.patch.object(commands, "start") as start, mock.patch.object(commands, "start_claude_only", return_value=0) as alone, \
+ contextlib.redirect_stdout(io.StringIO()) as out:
+ self.assertEqual(guide.run(type("Args", (), {})()), 0)
+ aws_choices.assert_not_called()
+ start.assert_not_called()
+ alone.assert_called_once()
+ self.assertIn("Claude only", out.getvalue())
+
+
+class Pipeline2Test(unittest.TestCase):
+ def test_program_names_follow_the_profile(self):
+ self.assertEqual(retrieve.program_of("app/cbl/PROG1.cbl"), "PROG1")
+ self.assertEqual(retrieve.program_of("./src/main/java/org/x/OrderService.java", "java"), "src/main/java/org/x/OrderService.java")
+ cards = retrieve.parse_rules(JAVA_RULE, "java")
+ self.assertEqual([c["program"] for c in cards],
+ ["src/main/java/org/demo/shop/service/OrderService.java", "src/main/java/org/demo/admin/OrderService.java"])
+ self.assertEqual([c["program"] for c in retrieve.parse_rules(JAVA_RULE)], ["ORDERSERVICE", "ORDERSERVICE"]) # the mainframe rule
+
+ def test_a_rule_joins_its_module_by_file_outside_the_mainframe(self):
+ model = {"modules": [{"id": "m1", "name": "OrderService", "domain": "dom:orders", "file": "src/main/java/org/demo/shop/service/OrderService.java"}],
+ "rules": [{"id": "RULE-001", "program": "src/main/java/org/demo/shop/service/OrderService.java", "domain": ""},
+ {"id": "RULE-002", "program": "src/main/java/org/demo/admin/OrderService.java", "domain": ""}],
+ "flows": []}
+ given = requirements.domain_input(model, {"id": "dom:orders", "name": "Orders", "members": ["m1"]})
+ self.assertEqual([r["id"] for r in given["rules"]], ["RULE-001"]) # the other OrderService stays apart
+ self.assertEqual(retrieve.module_keys(model["modules"][0]), {"ORDERSERVICE", "SRC/MAIN/JAVA/ORG/DEMO/SHOP/SERVICE/ORDERSERVICE.JAVA"})
+
+
+if __name__ == "__main__":
+ unittest.main()
From 5120242f832c613e74d5c61d44ba889e1d11e6ec Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 08:05:58 -0700
Subject: [PATCH 3/8] L1-03: a reconciliation in the stack's words
The reconciliation takes its words and its source files from the stack
profile (docs/any-legacy.md, section 5.3).
- The prompts of the decision, the description of agreed rules and the
accuracy audit are written for the mainframe, and for a mainframe run
they are exactly as before. For any other stack, Reframe puts them in
the stack's words: readers "who do not read Java and JSP"; "follow a
call, an include, an import or an inherited method" in place of "a
PERFORM, CALL or copybook"; and the reachability check speaks of entry
points reached from a route, a page or form, a menu, a call, an event
or a scheduled job, not of XCTL, LINK and job cards. The rules keep
their business form (WHEN ..., THE ... SHALL ...).
- The source files read are those of the profile's languages. For any
family but the mainframe, each file stands for itself, keyed by its
path, as its program name is (L1-02). Libraries kept in the tree are
left out.
- The evidence check is unchanged: every cited line must exist in the
snapshot.
- The expert's pack says which stack the source is, and its guide uses
the stack's words.
Tests: every mainframe prompt is the same object as before; Java's and
.NET's words; the source files and the evidence check on the Java
fixture; the audit's prompts and the expert's pack on a Java run.
Prepared with AI assistance.
---
src/reframe/reconcile/audit.py | 3 +-
src/reframe/reconcile/decide.py | 3 +-
src/reframe/reconcile/describe.py | 3 +-
src/reframe/reconcile/expert.py | 11 ++-
src/reframe/reconcile/inputs.py | 23 ++++--
src/reframe/source/profile.py | 30 +++++++-
tests/reconcile/test_stack_words.py | 112 ++++++++++++++++++++++++++++
7 files changed, 168 insertions(+), 17 deletions(-)
create mode 100644 tests/reconcile/test_stack_words.py
diff --git a/src/reframe/reconcile/audit.py b/src/reframe/reconcile/audit.py
index 3973c381..77736290 100644
--- a/src/reframe/reconcile/audit.py
+++ b/src/reframe/reconcile/audit.py
@@ -205,7 +205,8 @@ def one(number: int, batch: list[dict[str, Any]]) -> None:
step_name = f"audit-{label}-b{number}{'-retry' if attempt == 2 else ''}"
path = work / f"{step_name}.json"
path.write_text(json.dumps({"items": [shown(i, i["id"] in with_note) for i in pending.values()]}, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
if attempt == 2:
prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items()))
step = claude.run(step_name, prompt, timeout=3600, schema=SCHEMA)
diff --git a/src/reframe/reconcile/decide.py b/src/reframe/reconcile/decide.py
index 0b347869..8ad8db37 100644
--- a/src/reframe/reconcile/decide.py
+++ b/src/reframe/reconcile/decide.py
@@ -211,7 +211,8 @@ def _prompt(self, path: Path) -> str:
+ ("; " if documents and answers else "")
+ (f"answered SME questions in analysis/{project}/reframe/reconcile/{self.name}-answers.json" if answers else "") + ".")
from reframe.reconcile.units import one_tool
- return one_tool(self.folder, PROMPT.format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}",
+ from reframe.source import profile
+ return one_tool(self.folder, profile.in_words(PROMPT, profile.of_run(self.folder)).format(input=f"analysis/{project}/{path.relative_to(self.places['analysis']).as_posix()}",
legacy=f"legacy/{project}", context=context, kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE), ONE_TOOL)
def answers(self) -> list[dict[str, Any]]:
diff --git a/src/reframe/reconcile/describe.py b/src/reframe/reconcile/describe.py
index 5e31e46d..89ae5db9 100644
--- a/src/reframe/reconcile/describe.py
+++ b/src/reframe/reconcile/describe.py
@@ -122,7 +122,8 @@ def one(b: dict[str, Any]) -> None:
path = folder_in / f"{name}{'-retry' if attempt == 2 else ''}.json"
path.write_text(json.dumps({"rules": [{"key": i["key"], "program": i["program"], "name": i["name"], "text": i["text"], "cites": i["cites"]}
for i in todo.values()]}, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
kinds=KIND_GUIDE, examples=EXAMPLE_GUIDE)
if attempt == 2:
prompt += "\n\n" + RETRY.format(problems="\n".join(f"- {k}: {'; '.join(v)}" for k, v in failed.items()))
diff --git a/src/reframe/reconcile/expert.py b/src/reframe/reconcile/expert.py
index 2790ec9c..d8f9c0b0 100644
--- a/src/reframe/reconcile/expert.py
+++ b/src/reframe/reconcile/expert.py
@@ -77,7 +77,7 @@ def blind(item: dict[str, Any], with_note: bool) -> dict[str, Any]:
"defect_note": item["defect_note"] if with_note else ""}
-def page(rows: list[dict[str, Any]], project: str, origin: str) -> str:
+def page(rows: list[dict[str, Any]], project: str, origin: str, guide_text: str = GUIDE) -> str:
def code(ex: dict[str, Any]) -> str:
if ex["missing"]:
return f"
The modernized application's design, from the reconciled requirements and rules: the screens, the journeys, and a final specification
for every capability. A capability in a signed-off function is final; every other one is draft. Reframe assembled each specification and checked
every requirement, rule, screen and copybook it cites; a Claude step per function wrote the summaries, {c['written']} acceptance criteria for requirements
diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py
index f90ac536..78823390 100644
--- a/src/reframe/design/package.py
+++ b/src/reframe/design/package.py
@@ -502,10 +502,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
files[f"{base}/design.md"] = design_md(s, books)
files[f"{base}/tasks.md"] = tasks_md(s, ts[s["id"]])
# Claude Code
+ has_ui = bool(prototype and prototype.is_file()) # a codebase with no screens has no prototype (L1-04)
index = "\n".join(f"- [{s['id']} {md(s['title'])}](specs/{s['folder']}.md): {s['status']}, {s['runs_as']}" for s in specs)
files["claude-code/CLAUDE.md"] = "\n".join([
f"# {project}, modernized", "", "Build the modernized application from the specifications here. Each capability's specification is in `specs/`; "
- "the build tasks, each for a role, are in `tasks.md`; the prototype in `ui-reference/index.html` is the UI to build to; the data contracts are in "
+ "the build tasks, each for a role, are in `tasks.md`; " + ("the prototype in `ui-reference/index.html` is the UI to build to; " if has_ui else
+ "the legacy codebase has no screens, so there is no prototype: the capabilities run as jobs or services; ") + "the data contracts are in "
"`data-contracts.md`; `traceability.md` takes every ID back to the legacy source.", "", "## Target stack", "", stack_md(stack, context.get("architecture", "")), "",
"## Conventions", ""] + conventions() + ["", "## House conventions", "", handover.house(context.get("style", "")), "",
"## Skills", "", "In `.claude/skills/`: " + ", ".join(f"`{n}`" for n in handover.SKILLS) + ". Fill in their placeholders first; START-HERE.md says how.", "",
@@ -514,7 +516,8 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n"
for s in specs:
files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books)
- files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. "
+ if has_ui:
+ files["claude-code/ui-reference/README.md"] = ("# UI reference\n\n`index.html` is Reframe's clickable prototype of the modern screens: open it in a browser. "
"Each screen is a route (`#/`); *Show the legacy screen* shows the 3270 screen it replaces.\n")
# Spec Kit
files["spec-kit/.specify/memory/constitution.md"] = "\n".join([
@@ -653,7 +656,7 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
books = (folder.load("design/contracts.json") or {}).get("contracts") or {}
stack = folder.load(STACK) or None
journeys = (folder.load("design/journeys.json") or {}).get("journeys") or []
- prototype = folder.path("outputs/design/prototype/index.html")
+ prototype = None if (folder.load("design/modern.json") or {}).get("left_out") else folder.path("outputs/design/prototype/index.html")
project = folder.state.get("project") or "the application"
have = versions(folder)
latest = folder.path(f"{FOLDER}/v{have[-1]}") if have else None
diff --git a/src/reframe/design/pipeline.py b/src/reframe/design/pipeline.py
index f1c4d961..3d17a206 100644
--- a/src/reframe/design/pipeline.py
+++ b/src/reframe/design/pipeline.py
@@ -223,6 +223,9 @@ def changes_md(n: int, report: dict[str, Any]) -> str:
out += ["## The context", ""] + [f"- Added {f}" for f in ctx["added"]] + [f"- Changed {f}" for f in ctx["changed"]] + [f"- Removed {f}" for f in ctx["removed"]] + [""]
for stage, title in (("journeys", "Journeys"), ("screens", "Modern screens"), ("specs", "Final specifications")):
r = report["stages"].get(stage) or {"redone": [], "kept": []}
+ if r.get("left_out"):
+ out += [f"## {title}", "", "- Left out: the codebase has no screens.", ""]
+ continue
out += [f"## {title}", ""]
out += [f"- Made: {x['name'] or 'No domain'} (new)." if x["changed"] == ["new"] else f"- Redone: {x['name'] or 'No domain'}, because {words(stage, x['changed'])}."
for x in r["redone"]]
@@ -242,6 +245,19 @@ def changes_md(n: int, report: dict[str, Any]) -> str:
return "\n".join(out).rstrip() + "\n"
+def without_screens(stack: dict[str, Any], found: dict[str, Any]) -> str:
+ """Why the design has no screens (L1-04, docs/any-legacy.md section 5.4), or "" when it has some: no reader found a
+ screen and the stack profile found no screen definitions, views, templates or forms."""
+ if found.get("screens") or (stack.get("has") or {}).get("ui", {}).get("count"):
+ return ""
+ has = stack.get("has") or {}
+ what = ("a batch system" if has.get("jobs", {}).get("count") and not has.get("routes", {}).get("count")
+ else "a service" if has.get("routes", {}).get("count") else "a library")
+ return (f"This codebase has no screens: it looks like {what}, and Reframe found no screen definitions, views, templates or forms in it. "
+ "The journeys, the modern screens and the prototype are left out; the final specifications, golden datasets, package and "
+ "backlog are written as for any codebase.")
+
+
def run(folder, claude, context: Path | None = None, stack: str | None = None, plan_only: bool = False) -> dict[str, Any]:
from reframe.claude.workspace import paths
from reframe.design import designpage, flow, flowpage, inventory, journeypage, journeys, legacy, modernpage, package, prototype, screens, specs
@@ -259,10 +275,15 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p
"context_files": {"added": sorted(set(got["files"]) - set(before)), "removed": sorted(set(before) - set(got["files"])),
"changed": sorted(f for f in got["files"] if f in before and before[f] != got["files"][f])},
"signoffs": got["signoffs"], "journey_signoffs": got["journey_signoffs"], "ignored": got["ignored"]}
+ from reframe.source import profile
+ left_out = without_screens(profile.of_run(folder), inventory.inventory(paths(folder)["legacy"]))
if plan_only:
- report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"]
- report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"]
- report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"])["round"]
+ if left_out:
+ report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out}
+ else:
+ report["stages"]["journeys"] = journeys.run(folder, claude, context, for_journeys, plan_only=True)["round"]
+ report["stages"]["screens"] = screens.run(folder, claude, context, for_screens, plan_only=True)["round"]
+ report["stages"]["specs"] = specs.run(folder, claude, stack, for_specs, plan_only=True, signoffs=got["signoffs"], screenless=bool(left_out))["round"]
report["note"] = "Screens and specifications whose journeys or screens a redone part changes are redone too; this plan cannot see those yet."
return report
folder.update(design={**state, "round": number, "status": "running", "context": str(context) if context else "", "started_at": iso()})
@@ -274,18 +295,23 @@ def run(folder, claude, context: Path | None = None, stack: str | None = None, p
linked["problems"] = flow.check(linked, legacy_folder)
folder.save("design/flow.json", linked)
flowpage.draw(folder, found, linked)
- value = journeys.run(folder, claude, context, for_journeys)
- journeypage.draw(folder, value)
- report["stages"]["journeys"] = value["round"]
- for_journeys, for_screens, for_specs = routers(folder, got, routed)
- value = screens.run(folder, claude, context, for_screens)
- modernpage.draw(folder, value)
- report["stages"]["screens"] = value["round"]
- data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"),
- (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "")
- prototype.draw(folder, data, got["tokens"])
+ if left_out: # a batch system, a service or a library: no journeys, modern screens or prototype, and the page says why
+ folder.save("design/journeys.json", {"journeys": [], "left_out": left_out})
+ folder.save("design/modern.json", {"screens": [], "domains": {}, "counts": {}, "left_out": left_out})
+ report["stages"]["journeys"] = report["stages"]["screens"] = {"redone": [], "kept": [], "left_out": left_out}
+ else:
+ value = journeys.run(folder, claude, context, for_journeys)
+ journeypage.draw(folder, value)
+ report["stages"]["journeys"] = value["round"]
+ for_journeys, for_screens, for_specs = routers(folder, got, routed)
+ value = screens.run(folder, claude, context, for_screens)
+ modernpage.draw(folder, value)
+ report["stages"]["screens"] = value["round"]
+ data = prototype.build(folder.load("design/screens.json"), folder.load("design/modern.json"), folder.load("design/journeys.json"),
+ (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or [], folder.state.get("project") or "")
+ prototype.draw(folder, data, got["tokens"])
for_journeys, for_screens, for_specs = routers(folder, got, routed)
- value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"])
+ value = specs.run(folder, claude, stack, for_specs, signoffs=got["signoffs"], screenless=bool(left_out))
designpage.draw(folder, value)
report["stages"]["specs"] = value["round"]
report["problems"] = value["problems"]
diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py
index faa0ed87..4ed7b603 100644
--- a/src/reframe/design/specs.py
+++ b/src/reframe/design/specs.py
@@ -397,7 +397,8 @@ def stack_of(folder, stack: str | None) -> dict[str, Any] | None:
return folder.load(STACK) or None
-def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = False, signoffs: list[dict[str, Any]] | None = None,
+ screenless: bool = False) -> dict[str, Any]:
"""D6. `more(name, data)` gives a batch's extra input for a round (the decisions that name its capabilities);
`signoffs` adds sign-offs read in the round; `plan_only` says what would be redone, and why, without a step."""
from reframe.claude.steps import stop_for
@@ -407,7 +408,7 @@ def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = F
project = folder.state["project"]
if not (folder.load("outputs/reconcile/requirements.json") or {}).get("functions"):
raise ValueError("run the reconciliation first")
- if not folder.load("design/modern.json"):
+ if not screenless and not folder.load("design/modern.json"): # a codebase with no screens has none to wait for (L1-04)
raise ValueError("run the screen inventory, the flow, the journeys and the modern screens first")
target = stack_of(folder, None if plan_only else stack)
types = data_contracts.stack_types(target)
diff --git a/tests/design/test_no_screens.py b/tests/design/test_no_screens.py
new file mode 100644
index 00000000..17e4a245
--- /dev/null
+++ b/tests/design/test_no_screens.py
@@ -0,0 +1,92 @@
+"""L1-04: a design without screens (docs/any-legacy.md, section 5.4). A batch or service codebase gets its specifications,
+golden datasets, package and backlog, with the journeys, modern screens and prototype left out and the page saying why."""
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from reframe.core.runfolder import new_run
+from reframe.design import pipeline
+from reframe.report import backlog
+from reframe.source import profile
+from tests import stacks
+from tests.design.test_specs import written
+from tests.reconcile.test_decide import FakeClaude
+
+FEE = "rec/u:fee/1"
+RULES = [{"key": FEE, "program": "src/main/java/org/demo/billing/InvoiceProcessor.java", "function": "Billing/Invoice", "kind": "business",
+ "name": "Late fee", "confidence": "high", "text": "WHEN an invoice is more than 30 days late, THE billing job SHALL add a late fee of 15.00",
+ "covers": ["u/fee-orig"], "evidence": ["src/main/java/org/demo/billing/InvoiceProcessor.java:12"],
+ "entry": ["src/main/java/org/demo/billing/BillingJobConfig.java:6"],
+ "examples": [{"given": [{"field": "daysLate", "value": "31"}, {"field": "balance", "value": "100.00"}], "then": "the amount due is 115.00"}]}]
+REQUIREMENTS = {
+ "complete": True,
+ "domains": [{"key": "billing", "name": "Billing", "functions": ["Billing/Invoice"]}],
+ "names": {"Billing/Invoice": {"name": "Invoice customers"}},
+ "functions": {"Billing/Invoice": {"capabilities": [{
+ "number": 1, "title": "Charge late fees", "story": "As the finance team, I want late invoices to carry a fee", "risk": "high", "touches": ["money"],
+ "questions": [], "tables": [],
+ "requirements": [{"code": "REQ-F-001", "kind": "functional", "pattern": "event-driven", "rules": [FEE],
+ "text": "When an invoice is more than 30 days late, the system shall add a late fee of 15.00."}]}]}},
+}
+
+
+def unexpected(data):
+ raise AssertionError("no journey or screen step runs for a codebase with no screens")
+
+
+class NoScreensTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name})
+ env.start()
+ self.addCleanup(env.stop)
+ self.folder = new_run("billing")
+ self.folder.update(project="billing", tools="claude")
+ legacy = stacks.write(self.folder.root / "claude" / "legacy" / "billing", stacks.BATCH)
+ self.folder.save(profile.FILE, profile.profile_folder(legacy))
+ self.folder.save("snapshot.json", {"sha256": "abc"})
+ self.folder.save("outputs/reconcile/requirements.json", REQUIREMENTS)
+ self.folder.save("outputs/reconcile/rules.json", {"rules": RULES})
+ self.folder.save("reconcile/questions.json", {"questions": []})
+ self.claude = FakeClaude(journeys=unexpected, screens=unexpected, specs=written)
+ self.claude.root = self.folder.root / "claude"
+
+ def test_the_reason_names_what_the_codebase_is(self):
+ stack = self.folder.load(profile.FILE)
+ why = pipeline.without_screens(stack, {"screens": []})
+ self.assertIn("it looks like a batch system", why)
+ self.assertEqual(pipeline.without_screens(stack, {"screens": [{"map": "M"}]}), "") # a reader found screens
+ java = profile.profile_folder(stacks.write(Path(self.tmp.name) / "web", stacks.JAVA_WEB))
+ self.assertEqual(pipeline.without_screens(java, {"screens": []}), "") # views exist: not left out
+
+ def test_specifications_golden_datasets_package_and_backlog_without_screens(self):
+ value = pipeline.run(self.folder, self.claude)
+ for stage in ("journeys", "screens"):
+ self.assertIn("no screens", value["stages"][stage]["left_out"])
+ self.assertEqual([c[0].split("-")[0] for c in self.claude.other_calls], ["specs"]) # only the specifications' step
+ self.assertEqual(value["stages"]["specs"]["redone"][0]["name"], "Billing/Invoice")
+ self.assertFalse(self.folder.path("outputs/design/prototype/index.html").exists())
+ self.assertIn("- Left out: the codebase has no screens.", self.folder.path("design/changes-1.md").read_text())
+ page = self.folder.path("outputs/design/index.html").read_text()
+ self.assertIn("No screens.", page)
+ self.assertNotIn('href="prototype/index.html"', page)
+ self.assertNotIn("legacy screens", page)
+ root = Path(value["package"]["path"])
+ claude_md = (root / "claude-code/CLAUDE.md").read_text()
+ self.assertIn("the legacy codebase has no screens, so there is no prototype", claude_md)
+ self.assertFalse((root / "claude-code/ui-reference").exists())
+ self.assertTrue(list(root.rglob("golden/*")), "golden datasets are written")
+ self.assertTrue(list((root / "kiro/.kiro/specs").iterdir()))
+ made = backlog.export(self.folder, "jira", Path(self.tmp.name) / "jira.csv")
+ self.assertEqual(made["counts"]["stories"], 1)
+
+ def test_the_plan_says_so_too(self):
+ plan = pipeline.run(self.folder, self.claude, plan_only=True)
+ self.assertIn("no screens", plan["stages"]["journeys"]["left_out"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From 41feba181c0d752bf9f0765c1aa09aa83c258db4 Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 08:19:57 -0700
Subject: [PATCH 5/8] L1-05: screens and flow from any stack
For a codebase that is not a mainframe, the design reads its screens and
the flow between them with a general reader, reframe.design.general
(docs/any-legacy.md, section 5.4). It gives the later stages the same
shapes the BMS and CICS readers give, so the journeys, the modern
screens and the prototype work as on the mainframe.
- Screens (D1): one Claude step per batch of the views, pages and forms
the stack profile found lists each screen's fields (name, label, kind,
validation) and actions (buttons, links, submits), each citing its
line. Reframe checks that every screen names a file of the batch and
every cited line exists. A failed answer is asked again once with the
reasons; then the screen is kept with no fields and the reasons, never
guessed.
- Flow (D2): links read with no model where a pattern settles them: an
href, a form's action, a redirect, Spring and JAX-RS route
annotations, Stripes' @UrlBinding, the ASP.NET MVC conventions
(Html.ActionLink, Html.BeginForm, View(), RedirectToAction) and a
script page's own path. The ends of a link are view files and routes,
and each route stands for the screens it renders, or those it
redirects to. A link no pattern settles goes to one Claude step,
checked the same way (its target must be a screen, a route or a file,
and its lines must exist). What fails twice stays unresolved.
- The code behind a screen is its view, the handlers that render it and
the classes they use, so a screen reaches the domain of the rules in
its service.
- The legacy screens page shows a general screen as its fields and
actions with their lines and its source file; the old page is not
drawn. The flow page and the design page say which reader made them.
- The journeys, modern screens and specifications prompts speak of
screens, actions and links, not 3270 maps and function keys, for any
stack but the mainframe, whose prompts are unchanged.
Tests: the Java, .NET and PHP fixtures' screens, links by pattern,
reach and the code behind each screen; an answer that fails twice; a
link only a model step settles; the prompts' words; and a whole design
round on the Java fixture through to the prototype and the
specifications.
Prepared with AI assistance.
---
src/reframe/design/designpage.py | 8 +-
src/reframe/design/flowpage.py | 16 +-
src/reframe/design/general.py | 458 +++++++++++++++++++++++++++++++
src/reframe/design/journeys.py | 5 +-
src/reframe/design/legacy.py | 36 ++-
src/reframe/design/pipeline.py | 21 +-
src/reframe/design/screens.py | 3 +-
src/reframe/design/specs.py | 3 +-
src/reframe/source/profile.py | 30 ++
tests/design/test_general.py | 228 +++++++++++++++
tests/source/test_profile.py | 2 +-
tests/stacks.py | 7 +-
12 files changed, 799 insertions(+), 18 deletions(-)
create mode 100644 src/reframe/design/general.py
create mode 100644 tests/design/test_general.py
diff --git a/src/reframe/design/designpage.py b/src/reframe/design/designpage.py
index 14a39571..393b9fbc 100644
--- a/src/reframe/design/designpage.py
+++ b/src/reframe/design/designpage.py
@@ -173,10 +173,16 @@ def draw(folder, value: dict[str, Any]) -> Path:
'
' if left_out else ""
+ links = (folder.load("design/flow.json") or {}).get("counts") or {}
+ reader = ("" if left_out else
+ f'\n
Screens and flow read by Reframe\'s general reader: each view\'s fields and actions by a Claude step whose '
+ f'every cited line Reframe checked; {links.get("by_pattern", 0)} links by the code\'s patterns with no model, {links.get("by_model", 0)} by a '
+ f'checked Claude step, {links.get("unresolved", 0)} left open.
' if inventory.get("reader") == "general" else
+ '\n
Screens and flow read by Reframe\'s BMS and CICS readers, with no model.
')
body = f"""
The design
{nav}
-
The design
{why}
+
The design
{why}{reader}
The modernized application's design, from the reconciled requirements and rules: the screens, the journeys, and a final specification
for every capability. A capability in a signed-off function is final; every other one is draft. Reframe assembled each specification and checked
every requirement, rule, screen and copybook it cites; a Claude step per function wrote the summaries, {c['written']} acceptance criteria for requirements
diff --git a/src/reframe/design/flowpage.py b/src/reframe/design/flowpage.py
index 54e77e35..673007b7 100644
--- a/src/reframe/design/flowpage.py
+++ b/src/reframe/design/flowpage.py
@@ -15,7 +15,8 @@
from reframe.design.legacy import STYLE
PAGE = "outputs/design/flow.html"
-KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction"}
+KINDS = {"key": "key", "xctl": "transfer (XCTL)", "link": "call (LINK)", "return": "next transaction", "transaction": "transaction",
+ "href": "link", "form": "form", "redirect": "redirect", "renders": "renders"} # the last four: the general reader's (L1-05)
def _cites(lines: list[str]) -> str:
@@ -160,15 +161,20 @@ def draw(folder, screens: dict[str, Any], found: dict[str, Any]) -> Path:
+ (f" · from {', '.join(_target(c, screens_of, titles) for c in comes)}" if comes else "") + "
"
+ ('
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..d3f148e1
--- /dev/null
+++ b/src/reframe/design/general.py
@@ -0,0 +1,458 @@
+"""Pipeline 4, stages D1 and D2 for any stack: the general reader (L1-05, docs/any-legacy.md section 5.4).
+
+For a codebase that is not a mainframe, the design reads its screens and the flow between them from the views, pages and
+forms the stack profile found, and gives later stages the same shapes the BMS and CICS readers give (design/screens.json
+and design/flow.json), so the journeys, the modern screens and the prototype work as they do on the mainframe.
+
+- **Screens (D1):** one Claude step per batch of view files lists each screen's fields (name, label, kind, validation)
+ and actions (buttons, links, submits), each citing its line. Reframe checks the answer: every screen names a file of
+ the batch, every cited line exists. An answer that fails is asked again once with the reasons; then the file's screen
+ is kept with no fields and the reasons, never guessed.
+- **Flow (D2):** links read with no model where a pattern settles them: an `href`, a form's `action`, a redirect, a
+ route annotation (`@RequestMapping` and its kin, `@UrlBinding`, `@Path`), the MVC conventions (a controller's action
+ renders `Views//`, `return "orders/list"` renders that view), and a script page's own path. A link
+ no pattern settles goes to one Claude step, checked the same way: its target must be a screen, a route or a file that
+ exists, and its lines must exist. What fails twice stays unresolved.
+
+Every link and field cites `:` in the snapshot. Nothing here changes the source.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from collections import defaultdict
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+FILE = "design/general.json"
+BATCH_FILES, BATCH_BYTES = 8, 60_000
+METHOD = "general-1"
+
+SCREENS_PROMPT = """Read {input}. It holds the view, page and form files of a legacy {languages} application, each with its lines numbered. The legacy source is under {legacy}/ if you need more; do not change anything.
+
+For each file, give the screen it shows ("files", one entry per file, "file" exactly as listed): its "title" (what a user would call the screen), and
+- "fields": every data field: "name" (the input's name or the property it binds, as written), "label" (the visible label, or empty), "kind" ("input" for what the person enters or chooses, "output" for what the screen only shows), "validation" (what the markup or the code checks for it: required, a length, a range, a pattern; empty if nothing) and "line" (the line it is on);
+- "actions": every button, link and submit: "label" (as shown), "kind" ("button", "link" or "submit"), "target" (the URL, route, action or file it goes to, exactly as written, or empty) and "line".
+
+Use only what the files show. Cite only lines that exist. A file that is a fragment or layout with no fields or actions of its own gets empty lists. Answer only with the JSON."""
+
+LINKS_PROMPT = """Read {input}. It holds the links in a legacy {languages} application whose target Reframe could not settle from the code's patterns, each with the lines it was found on, and the screens and routes Reframe knows. The legacy source is under {legacy}/; do not change anything.
+
+For each link ("links", one entry per link, "id" exactly as listed), say what it leads to: "to" is a screen id from "screens", a route from "routes", a source file path relative to {legacy}/, or empty if the source cannot show it; "lines" are the lines that show it, as ":". Answer only with the JSON."""
+
+RETRY = """Your answer failed Reframe's checks. Answer again with the whole JSON, fixing these:
+
+{problems}"""
+
+SCREENS_SCHEMA = {"type": "object", "required": ["files"], "properties": {"files": {"type": "array", "items": {
+ "type": "object", "required": ["file", "title", "fields", "actions"], "properties": {
+ "file": {"type": "string"}, "title": {"type": "string"},
+ "fields": {"type": "array", "items": {"type": "object", "required": ["name", "label", "kind", "validation", "line"], "properties": {
+ "name": {"type": "string"}, "label": {"type": "string"}, "kind": {"type": "string", "enum": ["input", "output"]},
+ "validation": {"type": "string"}, "line": {"type": "integer"}}}},
+ "actions": {"type": "array", "items": {"type": "object", "required": ["label", "kind", "target", "line"], "properties": {
+ "label": {"type": "string"}, "kind": {"type": "string", "enum": ["button", "link", "submit"]}, "target": {"type": "string"},
+ "line": {"type": "integer"}}}}}}}}}
+LINKS_SCHEMA = {"type": "object", "required": ["links"], "properties": {"links": {"type": "array", "items": {
+ "type": "object", "required": ["id", "to", "lines"], "properties": {"id": {"type": "string"}, "to": {"type": "string"},
+ "lines": {"type": "array", "items": {"type": "string"}}}}}}}
+
+
+def _hash(value: Any) -> str:
+ return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()[:16]
+
+
+def _lines(legacy: Path, rel: str) -> list[str]:
+ try:
+ return (legacy / rel).read_text(errors="replace").splitlines()
+ except OSError:
+ return []
+
+
+def screen_id(rel: str, taken: set[str]) -> str:
+ """A screen's id from its file: the path without the usual view folders and the extension, in capitals."""
+ p = PurePosixPath(rel)
+ parts = [x for x in p.with_suffix("").parts if x.lower() not in {"src", "main", "webapp", "web-inf", "jsp", "views", "templates", "pages",
+ "resources", "public", "app", "web"}] or [p.stem]
+ base = re.sub(r"[^A-Z0-9]+", "-", "-".join(parts[-3:]).upper()).strip("-") or "SCREEN"
+ name, n = base, 2
+ while name in taken:
+ name, n = f"{base}-{n}", n + 1
+ taken.add(name)
+ return name
+
+
+def batches(views: list[str], legacy: Path) -> list[list[str]]:
+ out: list[list[str]] = [[]]
+ size = 0
+ for v in views:
+ n = (legacy / v).stat().st_size if (legacy / v).is_file() else 0
+ if out[-1] and (len(out[-1]) >= BATCH_FILES or size + n > BATCH_BYTES):
+ out.append([])
+ size = 0
+ out[-1].append(v)
+ size += n
+ return [b for b in out if b]
+
+
+def screen_problems(answer: dict[str, Any] | None, batch: list[str], legacy: Path) -> list[str]:
+ if not answer or not isinstance(answer.get("files"), list):
+ return ["no answer"]
+ found, seen = [], set()
+ for f in answer["files"]:
+ name = f.get("file")
+ if name not in batch:
+ found.append(f"{name}: not a file of this batch")
+ continue
+ seen.add(name)
+ count = len(_lines(legacy, name))
+ for what in ("fields", "actions"):
+ for item in f.get(what) or []:
+ if not 1 <= int(item.get("line") or 0) <= count:
+ found.append(f"{name}: {what[:-1]} {item.get('name') or item.get('label')!r} cites line {item.get('line')}, which {name} does not have ({count} lines)")
+ if not str(f.get("title") or "").strip():
+ found.append(f"{name}: no title")
+ found += [f"{name}: missing from the answer" for name in batch if name not in seen]
+ return found
+
+
+def _numbered(legacy: Path, rel: str) -> str:
+ return "\n".join(f"{n:5} {line}" for n, line in enumerate(_lines(legacy, rel), 1))
+
+
+def read_screens(folder, claude, legacy: Path, views: list[str], words: str, plan_only: bool = False) -> dict[str, Any]:
+ """D1 for any stack: the screens of the view files, in the inventory's shape, each made by a checked Claude step."""
+ from reframe.claude.steps import stop_for
+ from reframe.claude.workspace import paths
+ from reframe.design import rounds
+ places = paths(folder)
+ project = folder.state["project"]
+ saved = folder.load(FILE, {}) or {}
+ kept, log = saved.get("screens") or {}, saved.get("log") or []
+ todo, why, plan = [], [], {}
+ for i, batch in enumerate(batches(views, legacy), 1):
+ data = {"files": [{"file": v, "lines": _numbered(legacy, v)} for v in batch]}
+ key, digest = f"b{i}", _hash([data, METHOD])
+ if (kept.get(key) or {}).get("hash") != digest or (kept.get(key) or {}).get("problems"):
+ todo.append((key, batch, data, digest))
+ why.append((key, rounds.changed(kept.get(key), rounds.parts(data, METHOD))))
+ plan = rounds.summary(why, [k for k in kept if k not in {t[0] for t in todo}])
+ if plan_only:
+ return {"round": plan}
+ folder_in = places["analysis"] / "reframe" / "design"
+ folder_in.mkdir(parents=True, exist_ok=True)
+ for key, batch, data, digest in todo:
+ path = folder_in / f"reader-screens-{key}.json"
+ path.write_text(json.dumps(data, indent=1))
+ prompt = SCREENS_PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
+ languages=words)
+ answer, wrong = None, ["no answer"]
+ for attempt in (1, 2):
+ step = claude.run(f"reader-screens-{key}{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else
+ prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=SCREENS_SCHEMA)
+ log.append({"part": key, "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}})
+ if not step.ok:
+ if step.problem in ("limit", "signin"):
+ folder.save(FILE, {**saved, "screens": kept, "log": log})
+ raise stop_for(step, "the screens")
+ wrong = [f"the step did not finish ({step.problem})"]
+ continue
+ answer = claude.structured(step)
+ wrong = screen_problems(answer, batch, legacy)
+ if not wrong:
+ break
+ good = [] if wrong else (answer or {}).get("files") or []
+ kept[key] = {"hash": digest, "parts": rounds.parts(data, METHOD), "files": batch, "answer": good, "problems": wrong}
+ folder.save(FILE, {**saved, "screens": kept, "log": log})
+ taken: set[str] = set()
+ screens = []
+ for key in sorted(kept, key=lambda k: int(k[1:])):
+ part = kept[key]
+ answered = {f["file"]: f for f in part["answer"]}
+ for rel in part["files"]:
+ if rel not in views:
+ continue
+ f = answered.get(rel) or {"title": "", "fields": [], "actions": []}
+ screens.append(as_screen(rel, f, screen_id(rel, taken), part["problems"]))
+ value = {"reader": "general", "screens": screens, "maps": len(screens), "mapsets": len(screens), "fields": sum(len(s["fields"]) for s in screens),
+ "problems": sum(len(s["problems"]) for s in screens), "steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)}
+ folder.save(FILE, {**(folder.load(FILE, {}) or {}), "screens": kept, "log": log})
+ return {**value, "round": plan}
+
+
+def as_screen(rel: str, answer: dict[str, Any], sid: str, problems: list[str]) -> dict[str, Any]:
+ """One view in the inventory's shape (reframe.design.inventory): fields, keys (its actions), programs and problems."""
+ fields = [{"name": str(f.get("name") or ""), "kind": f.get("kind", "input"), "label": str(f.get("label") or ""),
+ "validation": str(f.get("validation") or ""), "line": int(f.get("line") or 0), "column": 1, "length": 0,
+ "attributes": [f["validation"]] if f.get("validation") else [], "color": "", "highlight": "", "initial": "", "picin": "",
+ "picout": "", "justify": "", "occurs": 0, "source_line": int(f.get("line") or 0)} for f in answer.get("fields") or []]
+ shown, seen = [], set()
+ for a in answer.get("actions") or []:
+ key = str(a.get("label") or a.get("target") or "action").strip()[:60]
+ if key in seen:
+ continue
+ seen.add(key)
+ shown.append({"key": key, "says": key, "kind": a.get("kind", ""), "target": str(a.get("target") or ""), "line": int(a.get("line") or 0)})
+ return {"reader": "general", "mapset": sid, "map": sid, "title": str(answer.get("title") or "") or sid.replace("-", " ").title(), "file": rel,
+ "source_line": 1, "size": [0, 0], "symbolic": "", "programs": [{"name": rel, "file": rel}], "fields": fields,
+ "counts": {k: sum(1 for f in fields if f["kind"] == k) for k in ("input", "output", "label", "stopper")},
+ "keys": {"shown": shown, "handled": [], "shown_not_handled": [], "handled_not_shown": []},
+ "problems": [f"the reader's answer failed twice: {p}" for p in problems]}
+
+
+# ---- D2: the flow ------------------------------------------------------------------------------------------------------
+
+JAVA_CLASS_ROUTE = re.compile(r"@(?:RequestMapping|Path|UrlBinding)\(\s*(?:value\s*=\s*|path\s*=\s*)?\"([^\"]*)\"")
+JAVA_METHOD_ROUTE = re.compile(r"@(?:GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping|RequestMapping|Path)(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?\"([^\"]*)\")?")
+RETURN_VIEW = re.compile(r"return\s+\"([^\":]+)\"\s*;")
+REDIRECT = re.compile(r"\"redirect:([^\"?]+)|RedirectToAction\(\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?|header\(\s*'Location:\s*([^'?]+)|Location:\s*([^\"'?\s]+)")
+HREF = re.compile(r"\b(href|action)\s*=\s*[\"']([^\"'#]+)")
+ACTION_LINK = re.compile(r"Html\.ActionLink\(\s*\"[^\"]*\"\s*,\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?") # (text, action[, controller])
+BEGIN_FORM = re.compile(r"Html\.BeginForm\(\s*\"(\w+)\"(?:\s*,\s*\"(\w+)\")?") # (action[, controller])
+CS_ACTION = re.compile(r"public\s+(?:async\s+)?(?:ActionResult|IActionResult|Task<\w+>|ViewResult)\s+(\w+)\s*\(")
+
+
+def _clean(url: str) -> str:
+ url = re.sub(r"\$\{[^}]*\}|<%=?[^%]*%>|@\{[^}]*\}|~", "", url.strip())
+ url = re.sub(r"/+", "/", url.split("?")[0].split("#")[0].strip())
+ return "/" + url.strip("/") if url else ""
+
+
+def routes(legacy: Path, files: list[str]) -> dict[str, dict[str, Any]]:
+ """Route -> {handler file, line, renders: [view names], redirects: [targets]}: read from the code with no model."""
+ found: dict[str, dict[str, Any]] = {}
+ for rel in files:
+ lines = _lines(legacy, rel)
+ suffix = PurePosixPath(rel).suffix.lower()
+ if suffix in (".java", ".kt", ".groovy"):
+ text = "\n".join(lines)
+ base = ""
+ cls = re.search(r"^\s*(?:public\s+)?(?:final\s+)?class\s", text, re.M)
+ head = text[:cls.start()] if cls else ""
+ m = JAVA_CLASS_ROUTE.search(head)
+ if m:
+ base = _clean(m.group(1))
+ for n, line in enumerate(lines, 1):
+ mm = JAVA_METHOD_ROUTE.search(line)
+ if mm and (not cls or n > text[:cls.start()].count("\n") + 1):
+ route = _clean(base + "/" + (mm.group(1) or "")) or base or "/"
+ body = "\n".join(lines[n:n + 40])
+ body = body.split("@GetMapping")[0].split("@PostMapping")[0].split("@RequestMapping")[0]
+ found.setdefault(route, {"handler": rel, "line": n, "renders": [], "redirects": []})
+ found[route]["renders"] += [v for v in RETURN_VIEW.findall(body)]
+ found[route]["redirects"] += [_clean(r[0]) for r in REDIRECT.findall(body) if r[0]]
+ elif suffix in (".cs", ".vb") and re.search(r"Controller\.(cs|vb)$", rel):
+ controller = re.sub(r"Controller\.(cs|vb)$", "", PurePosixPath(rel).name)
+ for n, line in enumerate(lines, 1):
+ m = CS_ACTION.search(line)
+ if not m:
+ continue
+ action = m.group(1)
+ body = "\n".join(lines[n:n + 40])
+ nxt = CS_ACTION.search(body)
+ body = body[:nxt.start()] if nxt else body
+ route = f"/{controller}/{action}"
+ renders = [f"{controller}/{action}"] if re.search(r"\bView\((?!\s*\")", body) else [] # View() or View(model): the action's own view
+ renders += [f"{controller}/{v}" for v in re.findall(r"\bView\(\s*\"(\w+)\"", body)]
+ redirects = [f"/{(r[2] or controller)}/{r[1]}" for r in REDIRECT.findall(body) if r[1]]
+ found.setdefault(route, {"handler": rel, "line": n, "renders": [], "redirects": []})
+ found[route]["renders"] += renders
+ found[route]["redirects"] += redirects
+ if action == "Index":
+ found.setdefault(f"/{controller}", found[route])
+ elif suffix in (".php", ".asp", ".pl", ".cgi", ".rb", ".py") or (suffix in (".jsp", ".html", ".htm") and "WEB-INF/" not in rel): # a page at its own path
+ redirects = [_clean(r[3] or r[4]) for r in REDIRECT.findall("\n".join(lines)) if (r[3] or r[4])]
+ found.setdefault("/" + rel, {"handler": rel, "line": 1, "renders": [rel] if suffix != ".py" else [], "redirects": redirects})
+ return found
+
+
+def resolve_view(name: str, views: dict[str, str]) -> str | None:
+ """A view name (`orders/list`, `Orders/Index`, or a page's path) -> the screen id whose file it names."""
+ name = name.strip("/").lower()
+ if not name:
+ return None
+ for rel, sid in views.items():
+ stem = PurePosixPath(rel).with_suffix("").as_posix().lower()
+ if rel.lower() == name or stem.endswith("/" + name) or stem == name:
+ return sid
+ return None
+
+
+def used_files(legacy: Path, rel: str, stems: dict[str, list[str]]) -> list[str]:
+ """The codebase's own files a handler uses, one level deep: the classes it names whose file is in the source."""
+ text = "\n".join(_lines(legacy, rel))
+ names = set(re.findall(r"\b([A-Z][A-Za-z0-9_]{2,})\b", text))
+ return sorted({f for n in names for f in stems.get(n, []) if f != rel})
+
+
+def read_flow(folder, claude, legacy: Path, screens: dict[str, Any], stack: dict[str, Any], plan_only: bool = False) -> dict[str, Any]:
+ """D2 for any stack: the links between screens, by pattern where one settles it and by a checked Claude step for the rest.
+ The ends of a link are view files and routes; each route stands for the screens it renders, or those it redirects to."""
+ from reframe.source import profile
+ views = {s["file"]: s["map"] for s in screens["screens"]}
+ code = sorted({p.relative_to(legacy).as_posix() for p in legacy.rglob("*") if p.is_file()
+ and not profile.is_library(p.relative_to(legacy).as_posix())
+ and profile.language(p.relative_to(legacy).as_posix(), p.read_bytes()[:4096]) not in (None, "SQL")})
+ stems: dict[str, list[str]] = defaultdict(list)
+ for rel in code:
+ stems[PurePosixPath(rel).stem].append(rel)
+ table = routes(legacy, code)
+ screens_of: dict[str, set[str]] = defaultdict(set)
+ for rel, sid in views.items():
+ screens_of[rel].add(sid)
+ links: list[dict[str, Any]] = []
+ unsettled: list[dict[str, Any]] = []
+ keys: list[dict[str, Any]] = []
+
+ def target_of(raw: str, where: str) -> str | None:
+ """A link as written -> a route Reframe knows, or a view file."""
+ url = _clean(raw)
+ relative = "/" + (PurePosixPath(where).parent / raw.split("?")[0]).as_posix().lstrip("/") if raw and not raw.startswith("/") else url
+ for candidate in (url, relative):
+ if candidate in table:
+ return candidate
+ sid = resolve_view(url, views) or resolve_view(relative, views)
+ return next(rel for rel, s in views.items() if s == sid) if sid else None
+
+ for route, r in table.items():
+ for v in r["renders"]:
+ sid = resolve_view(v, views)
+ if sid:
+ screens_of[route].add(sid)
+ links.append({"kind": "renders", "from": route, "to": next(rel for rel, x in views.items() if x == sid),
+ "lines": [f"{r['handler']}:{r['line']}"], "how": "pattern"})
+ for red in r["redirects"]:
+ to = target_of(red, r["handler"])
+ link = {"kind": "redirect", "from": route, "to": to or red, "lines": [f"{r['handler']}:{r['line']}"], "how": "pattern"}
+ (links if to else unsettled).append(link)
+ for _ in range(3): # a route that renders nothing stands for the screens its redirects reach
+ for link in links:
+ if link["kind"] == "redirect" and not any(x["kind"] == "renders" and x["from"] == link["from"] for x in links):
+ screens_of[link["from"]] |= screens_of.get(link["to"], set())
+ for s in screens["screens"]:
+ rel = s["file"]
+ targets: dict[str, list[str]] = defaultdict(list)
+ for n, line in enumerate(_lines(legacy, rel), 1):
+ found = [("form" if kind == "action" else "href", raw) for kind, raw in HREF.findall(line)
+ if not raw.startswith(("http:", "https:", "mailto:", "javascript:")) and not re.search(r"\.(css|js|png|jpe?g|gif|svg|ico)$", raw)]
+ for kind, pattern in (("href", ACTION_LINK), ("form", BEGIN_FORM)):
+ for m in pattern.finditer(line):
+ found.append((kind, f"/{m.group(2) or PurePosixPath(rel).parent.name}/{m.group(1)}"))
+ for kind, raw in found:
+ to = target_of(raw, rel)
+ link = {"kind": kind, "from": rel, "to": to or raw, "lines": [f"{rel}:{n}"], "how": "pattern"}
+ (links if to else unsettled).append(link)
+ if to:
+ targets[raw].append(to)
+ targets[raw.rsplit("/", 1)[-1]].append(to)
+ for k in s["keys"]["shown"]:
+ written = str(k.get("target") or "")
+ direct = target_of(written, rel) if written else None
+ leads = list(targets.get(written) or ([direct] if direct else []))
+ keys.append({"screen": s["map"], "key": k["key"], "to": sorted(set(leads))})
+ resolved, unresolved = settle(folder, claude, legacy, unsettled, views, table, stack, plan_only)
+ links += resolved
+ for s in screens["screens"]: # the code behind a screen: the handlers that render it and what they use
+ handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table})
+ used = sorted({f for h in handlers for f in used_files(legacy, h, stems)})
+ s["programs"] = [{"name": p, "file": p} for p in dict.fromkeys([s["file"], *handlers, *used])]
+ reached = {sid for link in links if link["kind"] != "renders" for sid in screens_of.get(link["to"], set())}
+ entries = {sid for r in ("/", "/index.php", "/index.html", "/index.jsp") for sid in screens_of.get(r, set())}
+ reach = [{"screen": s["map"], "reached": "navigated" if s["map"] in reached else "entry" if s["map"] in entries else "unreached"}
+ for s in screens["screens"]]
+ return {"reader": "general", "links": links, "keys": keys, "reach": reach, "unresolved": unresolved, "transactions": [],
+ "routes": {k: {"handler": v["handler"], "line": v["line"]} for k, v in sorted(table.items())},
+ "screens_of_programs": {k: sorted(v) for k, v in screens_of.items() if v},
+ "counts": {"by_pattern": sum(1 for x in links if x.get("how") == "pattern"), "by_model": sum(1 for x in links if x.get("how") == "model"),
+ "unresolved": len(unresolved)}}
+
+
+def link_problems(answer: dict[str, Any] | None, asked: list[dict[str, Any]], legacy: Path, views: dict[str, str], table: dict[str, Any]) -> list[str]:
+ if not answer or not isinstance(answer.get("links"), list):
+ return ["no answer"]
+ from reframe.reconcile.decide import missing_evidence
+ known, found, seen = {a["id"] for a in asked}, [], set()
+ for x in answer["links"]:
+ if x.get("id") not in known:
+ found.append(f"{x.get('id')}: not a link listed")
+ continue
+ seen.add(x["id"])
+ to = str(x.get("to") or "")
+ if to and to not in views.values() and to not in table and not (legacy / to).is_file():
+ found.append(f"{x['id']}: {to!r} is not a screen, a route or a file in the source")
+ bad = missing_evidence([str(c) for c in x.get("lines") or []], legacy)
+ if bad:
+ found.append(f"{x['id']}: lines that do not exist: {', '.join(bad)}")
+ found += [f"{i}: missing from the answer" for i in sorted(known - seen)]
+ return found
+
+
+def settle(folder, claude, legacy: Path, unsettled: list[dict[str, Any]], views: dict[str, str], table: dict[str, Any], stack: dict[str, Any],
+ plan_only: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """The links no pattern settled, by one checked Claude step; asked again once, then left unresolved."""
+ from reframe.claude.steps import stop_for
+ from reframe.claude.workspace import paths
+ if not unsettled or plan_only or claude is None:
+ return [], [{**x, "why": "no pattern settles it"} for x in unsettled]
+ asked = [{"id": f"L{n:03d}", "from": x["from"], "written": x["to"], "kind": x["kind"], "lines": x["lines"]} for n, x in enumerate(unsettled, 1)]
+ data = {"links": asked, "screens": [{"id": sid, "file": rel} for rel, sid in views.items()], "routes": sorted(table)}
+ saved = folder.load(FILE, {}) or {}
+ digest = _hash([data, METHOD])
+ before = saved.get("links") or {}
+ if before.get("hash") == digest and not before.get("problems"):
+ answer, wrong = before.get("answer"), []
+ else:
+ places, project = paths(folder), folder.state["project"]
+ folder_in = places["analysis"] / "reframe" / "design"
+ folder_in.mkdir(parents=True, exist_ok=True)
+ path = folder_in / "reader-links.json"
+ path.write_text(json.dumps(data, indent=1))
+ prompt = LINKS_PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}",
+ languages=stack["words"]["languages"])
+ answer, wrong = None, ["no answer"]
+ log = saved.get("log") or []
+ for attempt in (1, 2):
+ step = claude.run(f"reader-links{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else
+ prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=LINKS_SCHEMA)
+ log.append({"part": "links", "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}})
+ if not step.ok:
+ if step.problem in ("limit", "signin"):
+ folder.save(FILE, {**saved, "log": log})
+ raise stop_for(step, "the screen flow")
+ wrong = [f"the step did not finish ({step.problem})"]
+ continue
+ answer = claude.structured(step)
+ wrong = link_problems(answer, asked, legacy, views, table)
+ if not wrong:
+ break
+ folder.save(FILE, {**(folder.load(FILE, {}) or {}), "links": {"hash": digest, "answer": answer if not wrong else None, "problems": wrong}, "log": log})
+ if wrong:
+ return [], [{**x, "why": "; ".join(wrong)} for x in unsettled]
+ by_id = {x["id"]: x for x in (answer or {}).get("links") or []}
+ resolved, unresolved = [], []
+ sid_file = {sid: rel for rel, sid in views.items()}
+ for a, x in zip(asked, unsettled):
+ got = by_id.get(a["id"]) or {}
+ to = str(got.get("to") or "")
+ if not to:
+ unresolved.append({**x, "why": "the source cannot show where it leads"})
+ continue
+ to = sid_file.get(to) or to
+ resolved.append({**x, "to": to, "lines": x["lines"] + [c for c in got.get("lines") or [] if c not in x["lines"]], "how": "model"})
+ return resolved, unresolved
+
+
+def check(found: dict[str, Any], legacy: Path) -> list[str]:
+ """Every link's lines exist and it joins two things that exist (as reframe.design.flow.check does for the mainframe)."""
+ from reframe.reconcile.decide import missing_evidence
+ problems = []
+ for link in found["links"]:
+ bad = missing_evidence(link["lines"], legacy)
+ if bad:
+ problems.append(f"{link['kind']} {link['from']} -> {link['to']}: lines that do not exist: {', '.join(bad)}")
+ for end in (link["from"], link["to"]):
+ if end not in found.get("routes", {}) and not (legacy / end).is_file():
+ problems.append(f"{link['kind']} {link['from']} -> {link['to']}: {end} is not a route or a file in the source")
+ return problems
diff --git a/src/reframe/design/journeys.py b/src/reframe/design/journeys.py
index ccbddc2a..dbc7a86c 100644
--- a/src/reframe/design/journeys.py
+++ b/src/reframe/design/journeys.py
@@ -89,7 +89,7 @@ def screen_brief(s: dict[str, Any], full: bool) -> dict[str, Any]:
def label_for(f):
near = [t for (line, end), t in labels.items() if line == f["line"] and end <= f["column"] + 2 and t]
return near[-1] if near else ""
- brief["inputs"] = [{"field": f["name"], "label": label_for(f), "length": f["length"]} for f in s["fields"] if f["kind"] == "input"]
+ brief["inputs"] = [{"field": f["name"], "label": f.get("label") or label_for(f), "length": f["length"]} for f in s["fields"] if f["kind"] == "input"]
brief["shows"] = [f["name"] for f in s["fields"] if f["kind"] == "output"][:60]
brief["keys"] = [{"key": k["key"], "says": k["says"]} for k in s["keys"]["shown"]]
return brief
@@ -225,7 +225,8 @@ def one(item) -> None:
safe = "".join(c if c.isalnum() else "-" for c in (key or "no-domain")).strip("-")[:50]
path = folder_in / f"journeys-{safe}.json"
path.write_text(json.dumps(data, indent=1))
- prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
+ from reframe.source import profile
+ prompt = profile.in_words(PROMPT, profile.of_run(folder)).format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}")
answer, wrong, attempts = None, ["no answer"], 0
for attempt in (1, 2):
attempts = attempt
diff --git a/src/reframe/design/legacy.py b/src/reframe/design/legacy.py
index f25c28da..1cace778 100644
--- a/src/reframe/design/legacy.py
+++ b/src/reframe/design/legacy.py
@@ -45,7 +45,14 @@ def _color(f: dict[str, Any]) -> str:
def grid(screen: dict[str, Any]) -> str:
- """The screen as
text, a span per run of cells of one field."""
+ """The screen as
text, a span per run of cells of one field. A screen the general reader read (L1-05) has no
+ 3270 layout: it is shown as its field list, one line per field and action, citing the view's lines."""
+ if screen.get("reader") == "general":
+ rows = [f"{html.escape((f.get('label') or f['name'])[:40]):40} {'[' + html.escape(f['name']) + ']' if f['kind'] == 'input' else '<' + html.escape(f['name']) + '>'}"
+ + (f" ({html.escape(f['validation'])})" if f.get("validation") else "") + f" line {f['line']}" for f in screen["fields"]]
+ rows += [f"{'(' + html.escape(k.get('kind') or 'action') + ')':40} {html.escape(k['says'])}" + (f" → {html.escape(k['target'])}" if k.get("target") else "")
+ for k in screen["keys"]["shown"]]
+ return "
" + "\n".join(rows or ["(no fields or actions found)"]) + "
"
lines, columns = screen["size"]
chars = [[" "] * columns for _ in range(lines)]
owner: list[list[int | None]] = [[None] * columns for _ in range(lines)]
@@ -116,7 +123,29 @@ def _fields(screen: dict[str, Any]) -> str:
"
Initial 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.
+
The copybooks the capabilities' programs copy, as typed records, read from the source with no model.
{contracts}
+
Data contracts
{contracts_how}
{contracts}
What the checks still found
{problems}{more}
"""
target = folder.path(PAGE)
diff --git a/src/reframe/design/schema.py b/src/reframe/design/schema.py
new file mode 100644
index 00000000..3a4a54e6
--- /dev/null
+++ b/src/reframe/design/schema.py
@@ -0,0 +1,320 @@
+"""Pipeline 4, stage D6 for any stack: data contracts from the schema and the entities (L1-06, docs/any-legacy.md 5.4).
+
+For a codebase that is not a mainframe, the contracts come from what the stack profile found as data:
+
+- **SQL DDL,** read with no model: each `CREATE TABLE` is a record whose fields are its columns, each with its SQL type
+ as written, a neutral type (text of n characters, an integer, a decimal with its digits and scale, floating point, a
+ date, a timestamp, true or false, binary data), whether it may be empty, and its key (primary, or foreign to a table's
+ column), citing the line it is on;
+- **entity and record classes** (JPA, Entity Framework, plain classes the ORM maps), read by one Claude step per batch of
+ files: each entity with its fields, their types as written, the neutral type, the key and whether a value is
+ required, each citing its line. Reframe checks every cited line exists and shows the field's name; an answer that
+ fails is asked again once with the reasons, then the file is kept as unread, never guessed.
+
+The contracts have the copybooks' shape (reframe.design.contracts), so the specifications, the design page and the
+package use them as they are. The target stack's code and column types apply as for copybooks; a date, a timestamp, a
+boolean or binary data keeps its neutral type, since Reframe's type tables do not name those.
+
+A program (a source file, L1-02) uses a contract when its code names the table or the entity.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+FILE = "design/schema.json"
+METHOD = "schema-1"
+BATCH_FILES = 8
+NEUTRAL = ("text", "integer", "decimal", "float", "date", "timestamp", "time", "boolean", "binary")
+CODE = {".java", ".kt", ".groovy", ".cs", ".vb", ".py", ".rb", ".php"}
+
+PROMPT = """Read {input}. It holds entity and record classes of a legacy {languages} application, each with its lines numbered: the classes its code maps to stored data. The legacy source is under {legacy}/ if you need more; do not change anything.
+
+For each file ("files", one entry per file, "file" exactly as listed), give the entities it defines ("entities"): each with its "name" (the class), the "table" it is stored in if the code says (else empty), its "line", and its "fields": each with "name" (as written), "type" (as written), "neutral" (one of text, integer, decimal, float, date, timestamp, time, boolean, binary), "length" (for text, if the code gives one, else 0), "digits" and "scale" (for a decimal, if the code gives them, else 0), "key" ("primary", "foreign" or empty), "required" (true when the code says a value must be given) and "line" (the line the field is declared on).
+
+Use only what the files show. A file with no entity gets an empty list. Answer only with the JSON."""
+
+RETRY = """Your answer failed Reframe's checks. Answer again with the whole JSON, fixing these:
+
+{problems}"""
+
+SCHEMA = {"type": "object", "required": ["files"], "properties": {"files": {"type": "array", "items": {
+ "type": "object", "required": ["file", "entities"], "properties": {"file": {"type": "string"}, "entities": {"type": "array", "items": {
+ "type": "object", "required": ["name", "table", "line", "fields"], "properties": {
+ "name": {"type": "string"}, "table": {"type": "string"}, "line": {"type": "integer"},
+ "fields": {"type": "array", "items": {"type": "object", "required": ["name", "type", "neutral", "length", "digits", "scale", "key", "required", "line"],
+ "properties": {"name": {"type": "string"}, "type": {"type": "string"},
+ "neutral": {"type": "string", "enum": list(NEUTRAL)}, "length": {"type": "integer"},
+ "digits": {"type": "integer"}, "scale": {"type": "integer"},
+ "key": {"type": "string", "enum": ["primary", "foreign", ""]},
+ "required": {"type": "boolean"}, "line": {"type": "integer"}}}}}}}}}}}}
+
+
+# ---- neutral types -----------------------------------------------------------------------------------------------------
+
+def sql_type(written: str) -> dict[str, Any]:
+ """An SQL column type -> Reframe's neutral type."""
+ t = written.upper().strip()
+ m = re.match(r"(\w+(?:\s+(?:VARYING|PRECISION))?)\s*(?:\(\s*(\d+)\s*(?:,\s*(\d+)\s*)?\))?", t)
+ name, a, b = (m.group(1), int(m.group(2) or 0), int(m.group(3) or 0)) if m else (t, 0, 0)
+ if name in ("CHAR", "CHARACTER", "VARCHAR", "VARCHAR2", "NVARCHAR", "NCHAR", "CHARACTER VARYING", "TEXT", "CLOB", "STRING"):
+ return {"type": "text", "length": a, "storage": "characters", "bytes": a}
+ if name in ("SMALLINT", "INT", "INTEGER", "BIGINT", "TINYINT", "MEDIUMINT", "SERIAL", "BIGSERIAL"):
+ digits = {"TINYINT": 3, "SMALLINT": 5, "MEDIUMINT": 7, "BIGINT": 19, "BIGSERIAL": 19}.get(name, 10)
+ return {"type": "integer", "digits": digits, "scale": 0, "signed": True, "storage": "binary", "bytes": 8 if digits > 10 else 4}
+ if name in ("DECIMAL", "NUMERIC", "DEC", "NUMBER", "MONEY"):
+ return {"type": "decimal" if b else "integer", "digits": a or 18, "scale": b, "signed": True, "storage": "decimal", "bytes": 0}
+ if name in ("FLOAT", "REAL", "DOUBLE", "DOUBLE PRECISION"):
+ return {"type": "float", "storage": "double float" if name != "REAL" else "single float", "bytes": 8}
+ if name in ("DATE",):
+ return {"type": "date"}
+ if name in ("TIMESTAMP", "DATETIME", "DATETIME2", "TIMESTAMPTZ"):
+ return {"type": "timestamp"}
+ if name in ("TIME",):
+ return {"type": "time"}
+ if name in ("BOOLEAN", "BOOL", "BIT"):
+ return {"type": "boolean"}
+ if name in ("BLOB", "BINARY", "VARBINARY", "BYTEA", "IMAGE"):
+ return {"type": "binary"}
+ return {"type": "unknown"}
+
+
+def from_answer(f: dict[str, Any]) -> dict[str, Any]:
+ kind = f.get("neutral") or "unknown"
+ if kind == "text":
+ return {"type": "text", "length": int(f.get("length") or 0), "storage": "characters", "bytes": int(f.get("length") or 0)}
+ if kind in ("integer", "decimal"):
+ return {"type": kind, "digits": int(f.get("digits") or (18 if kind == "decimal" else 10)), "scale": int(f.get("scale") or 0),
+ "signed": True, "storage": "decimal" if kind == "decimal" else "binary", "bytes": 0}
+ if kind == "float":
+ return {"type": "float", "storage": "double float", "bytes": 8}
+ return {"type": kind}
+
+
+def says(t: dict[str, Any]) -> str:
+ from reframe.design.contracts import describe
+ kind = t.get("type")
+ if kind == "text":
+ return f"text, {t['length']} characters" if t.get("length") else "text"
+ if kind in ("integer", "decimal") and t.get("storage") in ("binary", "decimal"):
+ return (f"integer, {t['digits']} digits" if kind == "integer" else f"decimal, {t['digits'] - t['scale']} integer and {t['scale']} fraction digits")
+ return {"date": "date", "timestamp": "date and time", "time": "time of day", "boolean": "true or false", "binary": "binary data",
+ "unknown": "a type Reframe does not know"}.get(str(kind)) or describe(t)
+
+
+def typed(t: dict[str, Any], types: dict[str, Any]) -> dict[str, str]:
+ from reframe.design.contracts import on_stack
+ if t.get("type") == "text" and not t.get("length"):
+ return {} # a text of no stated length: Reframe gives no column size it was not told
+ return on_stack(t, types)
+
+
+# ---- SQL DDL, with no model --------------------------------------------------------------------------------------------
+
+CREATE = re.compile(r"\bCREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w.\"`\[\]]+)\s*\(", re.I)
+
+
+def _split(body: str) -> list[tuple[str, int]]:
+ """The comma-separated parts of a table body at depth 0, each with its offset."""
+ parts, depth, start = [], 0, 0
+ for i, ch in enumerate(body):
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ elif ch == "," and depth == 0:
+ parts.append((body[start:i], start))
+ start = i + 1
+ parts.append((body[start:], start))
+ return parts
+
+
+def tables(text: str, rel: str, types: dict[str, Any]) -> list[dict[str, Any]]:
+ """Every CREATE TABLE in one file, as contracts."""
+ found = []
+ for m in CREATE.finditer(text):
+ depth, end = 1, m.end()
+ while end < len(text) and depth:
+ depth += {"(": 1, ")": -1}.get(text[end], 0)
+ end += 1
+ body, base = text[m.end():end - 1], m.end()
+ name = m.group(1).strip('"`[]').split(".")[-1]
+ fields, primary, foreign = [], set(), {}
+ for part, offset in _split(body):
+ clause = " ".join(part.split())
+ if not clause:
+ continue
+ line = text[:base + offset + len(part) - len(part.lstrip())].count("\n") + 1
+ pk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?PRIMARY\s+KEY\s*\(([^)]*)\)", clause, re.I)
+ fk = re.match(r"(?:CONSTRAINT\s+\w+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s*REFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", clause, re.I)
+ if pk:
+ primary |= {c.strip().strip('"`').upper() for c in pk.group(1).split(",")}
+ continue
+ if fk:
+ foreign[fk.group(1).strip().strip('"`').upper()] = f"{fk.group(2).strip(chr(34) + '`')}({fk.group(3).strip()})"
+ continue
+ if re.match(r"(CONSTRAINT|UNIQUE|CHECK|INDEX|KEY)\b", clause, re.I):
+ continue
+ col = re.match(r"([\w\"`\[\]]+)\s+(.+)", clause)
+ if not col:
+ continue
+ cname, rest = col.group(1).strip('"`[]'), col.group(2)
+ written = re.match(r"[\w ]+?(?:\([^)]*\))?(?=\s+(?:NOT|NULL|DEFAULT|PRIMARY|REFERENCES|UNIQUE|CHECK|CONSTRAINT|GENERATED|AUTO_INCREMENT|IDENTITY)\b|\s*$)",
+ rest, re.I)
+ sql = (written.group(0) if written else rest.split()[0]).strip()
+ t = sql_type(sql)
+ ref = re.search(r"\bREFERENCES\s+([\w.\"`]+)\s*\(([^)]*)\)", rest, re.I)
+ if re.search(r"\bPRIMARY\s+KEY\b", rest, re.I):
+ primary.add(cname.upper())
+ if ref:
+ foreign[cname.upper()] = f"{ref.group(1).strip(chr(34) + '`')}({ref.group(2).strip()})"
+ field = {"name": cname, "level": 1, "group": "", "pic": sql, "usage": " ".join(rest[len(sql):].split()), **t, "says": says(t),
+ "line": line, "nullable": not re.search(r"\bNOT\s+NULL\b|\bPRIMARY\s+KEY\b", rest, re.I)}
+ stack = typed(t, types)
+ if stack:
+ field["stack"] = stack
+ fields.append(field)
+ for f in fields:
+ if f["name"].upper() in primary:
+ f["key"] = "primary"
+ elif f["name"].upper() in foreign:
+ f["key"] = f"foreign: {foreign[f['name'].upper()]}"
+ found.append({"copybook": name.upper(), "kind": "table", "file": rel, "how": "SQL DDL, read with no model",
+ "records": [{"name": name, "line": text[:m.start()].count("\n") + 1, "fields": fields}]})
+ return found
+
+
+# ---- entities, by a checked Claude step --------------------------------------------------------------------------------
+
+def _lines(legacy: Path, rel: str) -> list[str]:
+ try:
+ return (legacy / rel).read_text(errors="replace").splitlines()
+ except OSError:
+ return []
+
+
+def problems(answer: dict[str, Any] | None, batch: list[str], legacy: Path) -> list[str]:
+ if not answer or not isinstance(answer.get("files"), list):
+ return ["no answer"]
+ found, seen = [], set()
+ for f in answer["files"]:
+ name = f.get("file")
+ if name not in batch:
+ found.append(f"{name}: not a file of this batch")
+ continue
+ seen.add(name)
+ lines = _lines(legacy, name)
+ for e in f.get("entities") or []:
+ if not 1 <= int(e.get("line") or 0) <= len(lines):
+ found.append(f"{name}: entity {e.get('name')!r} cites line {e.get('line')}, which {name} does not have")
+ for x in e.get("fields") or []:
+ n = int(x.get("line") or 0)
+ if not 1 <= n <= len(lines):
+ found.append(f"{name}: field {x.get('name')!r} cites line {n}, which {name} does not have ({len(lines)} lines)")
+ elif str(x.get("name") or "") not in lines[n - 1]:
+ found.append(f"{name}: field {x.get('name')!r} is not on line {n}")
+ found += [f"{name}: missing from the answer" for name in batch if name not in seen]
+ return found
+
+
+def entities(folder, claude, legacy: Path, files: list[str], words: str, types: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]:
+ """The entity classes of the files, as contracts, and the problems left after the second answer."""
+ from reframe.claude.steps import stop_for
+ from reframe.claude.workspace import paths
+ saved = folder.load(FILE, {}) or {}
+ kept, log = saved.get("entities") or {}, saved.get("log") or []
+ places, project = paths(folder), folder.state["project"]
+ folder_in = places["analysis"] / "reframe" / "design"
+ left: list[str] = []
+ out: list[dict[str, Any]] = []
+ for i in range(0, len(files), BATCH_FILES):
+ batch = files[i:i + BATCH_FILES]
+ data = {"files": [{"file": f, "lines": "\n".join(f"{n:5} {x}" for n, x in enumerate(_lines(legacy, f), 1))} for f in batch]}
+ key = f"b{i // BATCH_FILES + 1}"
+ digest = hashlib.sha256(json.dumps([data, METHOD], sort_keys=True).encode()).hexdigest()[:16]
+ before = kept.get(key) or {}
+ if before.get("hash") != digest or before.get("problems"):
+ if claude is None:
+ left.append(f"{', '.join(batch)}: not read yet")
+ continue
+ folder_in.mkdir(parents=True, exist_ok=True)
+ path = folder_in / f"schema-entities-{key}.json"
+ path.write_text(json.dumps(data, indent=1))
+ prompt = PROMPT.format(input=f"analysis/{project}/{path.relative_to(places['analysis']).as_posix()}", legacy=f"legacy/{project}", languages=words)
+ answer, wrong = None, ["no answer"]
+ for attempt in (1, 2):
+ step = claude.run(f"schema-entities-{key}{'-retry' if attempt == 2 else ''}", prompt if attempt == 1 else
+ prompt + "\n\n" + RETRY.format(problems="\n".join(f"- {p}" for p in wrong)), timeout=3600, schema=SCHEMA)
+ log.append({"part": key, "attempt": attempt, **{k: v for k, v in step.as_json().items() if k in ("ok", "seconds", "tokens", "cost_usd", "problem")}})
+ if not step.ok:
+ if step.problem in ("limit", "signin"):
+ folder.save(FILE, {**saved, "entities": kept, "log": log})
+ raise stop_for(step, "the data contracts")
+ wrong = [f"the step did not finish ({step.problem})"]
+ continue
+ answer = claude.structured(step)
+ wrong = problems(answer, batch, legacy)
+ if not wrong:
+ break
+ before = kept[key] = {"hash": digest, "answer": None if wrong else answer, "problems": wrong}
+ folder.save(FILE, {**saved, "entities": kept, "log": log})
+ left += before.get("problems") or []
+ for f in (before.get("answer") or {}).get("files") or []:
+ for e in f.get("entities") or []:
+ fields = []
+ for x in e.get("fields") or []:
+ t = from_answer(x)
+ field = {"name": x["name"], "level": 1, "group": "", "pic": x.get("type", ""), "usage": "required" if x.get("required") else "",
+ **t, "says": says(t), "line": int(x["line"]), "nullable": not x.get("required")}
+ if x.get("key"):
+ field["key"] = x["key"]
+ stack = typed(t, types)
+ if stack:
+ field["stack"] = stack
+ fields.append(field)
+ out.append({"copybook": str(e["name"]).upper(), "kind": "entity", "file": f["file"], "table": e.get("table") or "",
+ "how": "entity class, read by a Claude step Reframe checked", "records": [{"name": e["name"], "line": int(e["line"]), "fields": fields}]})
+ return out, left
+
+
+# ---- all of it ---------------------------------------------------------------------------------------------------------
+
+def read(folder, claude, legacy: Path, stack: dict[str, Any], types: dict[str, Any]) -> dict[str, Any]:
+ """Every contract of a codebase that is not a mainframe: its tables, with no model, and its entities, by a checked step."""
+ from reframe.source import profile
+ data_files = profile.files_with(legacy, "data")
+ found: dict[str, dict[str, Any]] = {}
+ for rel in data_files:
+ if PurePosixPath(rel).suffix.lower() in (".sql", ".ddl"):
+ for c in tables((legacy / rel).read_text(errors="replace"), rel, types):
+ found.setdefault(c["copybook"], c)
+ code = [rel for rel in data_files if PurePosixPath(rel).suffix.lower() in CODE]
+ made, left = entities(folder, claude, legacy, code, stack["words"]["languages"], types)
+ for c in made:
+ name = c["copybook"] if c["copybook"] not in found else f"{c['copybook']}-ENTITY"
+ found[name] = {**c, "copybook": name}
+ return {"contracts": found, "problems": left}
+
+
+def uses(legacy: Path, contracts: dict[str, dict[str, Any]]) -> dict[str, dict[str, str]]:
+ """For each source file (the program, L1-02), the contracts its code names: a table by its name, an entity by its class."""
+ from reframe.source import kinds, profile
+ words = {name: {c["records"][0]["name"], *([c["table"]] if c.get("table") else [])} for name, c in contracts.items()}
+ found: dict[str, dict[str, str]] = {}
+ for p in sorted(legacy.rglob("*")):
+ if not p.is_file():
+ continue
+ rel = p.relative_to(legacy).as_posix()
+ if profile.is_library(rel) or profile.language(rel, kinds.read_head(p)) in (None, "SQL"):
+ continue
+ text = p.read_text(errors="replace")
+ mine = {name: ("table" if c["kind"] == "table" else "entity") for name, c in contracts.items()
+ if c["file"] != rel and any(re.search(rf"\b{re.escape(w)}\b", text, re.I if c["kind"] == "table" else 0) for w in words[name])}
+ mine.update({name: "entity" for name, c in contracts.items() if c["file"] == rel})
+ if mine:
+ found[rel.upper()] = mine
+ return found
diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py
index 958a7368..20ee13b4 100644
--- a/src/reframe/design/specs.py
+++ b/src/reframe/design/specs.py
@@ -191,7 +191,8 @@ def questions_for(rule_keys: list[str], rules: dict[str, Any], sme: list[dict[st
return found
-def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None = None,
+ contracts: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
"""Every capability's specification without the model's parts, and what the model step is to write for each."""
requirements = folder.load("outputs/reconcile/requirements.json") or {}
rules = {r["key"]: r for r in (folder.load("outputs/reconcile/rules.json") or {}).get("rules") or []}
@@ -205,7 +206,11 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None
signed[x["function"]].append({"reviewer": x.get("reviewer", ""), "at": x.get("at", ""), "comment": x.get("comment", "")})
online = {p["name"].upper() for s in inventory.get("screens") or [] for p in s.get("programs") or []} | \
{str(t.get("program", "")).upper() for t in flow.get("transactions") or []}
- uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {}
+ if contracts is not None: # any stack but the mainframe (L1-06): the tables and entities each source file names
+ from reframe.design import schema
+ uses = schema.uses(legacy, contracts) if legacy and legacy.is_dir() else {}
+ else:
+ uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {}
domain_of = {f: d for d in requirements.get("domains") or [] for f in d.get("functions") or []}
names = requirements.get("names") or {}
found = []
@@ -412,8 +417,18 @@ def run(folder, claude, stack: str | None = None, more=None, plan_only: bool = F
raise ValueError("run the screen inventory, the flow, the journeys and the modern screens first")
target = stack_of(folder, None if plan_only else stack)
types = data_contracts.stack_types(target)
- built = assemble(folder, places["legacy"], signoffs)
- books = data_contracts.contracts(places["legacy"], set(built["books"]), types)
+ from reframe.source import profile
+ stack_profile = profile.of_run(folder)
+ schema_problems: list[str] = []
+ if stack_profile.get("family", "mainframe") == "mainframe":
+ built = assemble(folder, places["legacy"], signoffs)
+ books = data_contracts.contracts(places["legacy"], set(built["books"]), types)
+ else: # the schema with no model and the entities by a checked step (L1-06)
+ from reframe.design import schema
+ read = schema.read(folder, None if plan_only else claude, places["legacy"], stack_profile, types)
+ schema_problems = [f"data contracts: {p}" for p in read["problems"]]
+ built = assemble(folder, places["legacy"], signoffs, read["contracts"])
+ books = {name: c for name, c in read["contracts"].items() if name in set(built["books"])}
if not plan_only:
folder.save(CONTRACTS, {"stack": target, "notes": types["notes"], "contracts": books})
saved = folder.load(FILE, {}) or {}
@@ -493,7 +508,7 @@ def one(item) -> None:
value = {"batches": kept, "log": log, "stack": target, "stack_notes": types["notes"],
"specs": [{k: s[k] for k in ("key", "function", "function_name", "domain", "number", "title", "status", "runs_as")} for s in specs],
"counts": counts(specs, books),
- "problems": batch_problems + found,
+ "problems": batch_problems + schema_problems + found,
"steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)}
folder.save(FILE, value)
value["full"] = specs
diff --git a/tests/design/test_general.py b/tests/design/test_general.py
index 6fb9d3ba..740ac1dd 100644
--- a/tests/design/test_general.py
+++ b/tests/design/test_general.py
@@ -91,7 +91,8 @@ def run_for(self, name, reader=read_views):
self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", stacks.FIXTURES[name])
self.stack = profile.profile_folder(self.legacy)
self.folder.save(profile.FILE, self.stack)
- self.claude = FakeClaude(reader=reader, journeys=journeys_for, screens=screens_for, specs=written)
+ from tests.design.test_schema import read_entities
+ self.claude = FakeClaude(reader=reader, journeys=journeys_for, screens=screens_for, specs=written, schema=read_entities)
self.claude.root = self.folder.root / "claude"
views = profile.files_with(self.legacy, "ui")
found = general.read_screens(self.folder, self.claude, self.legacy, views, self.stack["words"]["languages"])
@@ -221,7 +222,10 @@ def test_a_design_round_on_java(self):
self.assertIn("general reader", self.folder.path("outputs/design/legacy/index.html").read_text())
self.assertIn("Customer", self.folder.path("outputs/design/legacy/ORDERS-NEW.html").read_text())
self.assertIn("Read by Reframe's general reader", self.folder.path("outputs/design/flow.html").read_text())
- self.assertIn("general reader", self.folder.path("outputs/design/index.html").read_text())
+ page = self.folder.path("outputs/design/index.html").read_text()
+ self.assertIn("general reader", page)
+ self.assertIn("the tables read from the SQL DDL with no model", page) # L1-06: the service behind the rule names the Order entity
+ self.assertIn('id="contract-ORDER"', page)
if __name__ == "__main__":
diff --git a/tests/design/test_schema.py b/tests/design/test_schema.py
new file mode 100644
index 00000000..57b576ac
--- /dev/null
+++ b/tests/design/test_schema.py
@@ -0,0 +1,143 @@
+"""L1-06: data contracts from any stack (docs/any-legacy.md, section 5.4). SQL DDL is read with no model; entity classes
+by a checked model step; the target stack's types apply as today."""
+import os
+import re
+import tempfile
+import unittest
+from unittest import mock
+
+from reframe.core.runfolder import new_run
+from reframe.design import contracts, schema
+from reframe.source import profile
+from tests import stacks
+from tests.reconcile.test_decide import FakeClaude
+
+DDL = """-- the shop's schema
+CREATE TABLE CUSTOMER (
+ ID BIGINT NOT NULL,
+ NAME VARCHAR(40) NOT NULL,
+ CREDIT DECIMAL(9,2) DEFAULT 0,
+ JOINED DATE,
+ ACTIVE BOOLEAN,
+ PRIMARY KEY (ID)
+);
+CREATE TABLE IF NOT EXISTS ORDERS (
+ ID BIGINT PRIMARY KEY,
+ CUSTOMER_ID BIGINT NOT NULL REFERENCES CUSTOMER(ID),
+ TOTAL NUMERIC(10, 2),
+ NOTE TEXT,
+ CONSTRAINT FK_X FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER (ID)
+);
+"""
+JAVA_FIELD = re.compile(r"private\s+(\w+)\s+(\w+)\s*;")
+CS_FIELD = re.compile(r"public\s+(\w+)\s+(\w+)\s*\{\s*get;")
+NEUTRAL = {"String": "text", "string": "text", "int": "integer", "Long": "integer", "BigDecimal": "decimal", "decimal": "decimal"}
+
+
+def read_entities(data):
+ """What the step answers: each class's fields as declared, with the lines they are on."""
+ files = []
+ for f in data["files"]:
+ rows = [r.strip().partition(" ") for r in f["lines"].splitlines()]
+ found, fields, line_of = None, [], 0
+ for n, _, line in rows:
+ m = re.search(r"class\s+(\w+)", line)
+ if m and found is None:
+ found, line_of = m.group(1), int(n)
+ for pattern in (JAVA_FIELD, CS_FIELD):
+ for t, name in pattern.findall(line):
+ fields.append({"name": name, "type": t, "neutral": NEUTRAL.get(t, "text"), "length": 40 if name in ("customer", "Customer") else 0,
+ "digits": 0, "scale": 0, "key": "primary" if name in ("id", "Id") else "", "required": name in ("customer", "Customer"),
+ "line": int(n)})
+ entities = [{"name": found, "table": "ORDERS" if "ORDERS" in f["lines"] else "Orders" if "Orders" in f["lines"] else "", "line": line_of,
+ "fields": fields}] if found and fields else []
+ files.append({"file": f["file"], "entities": entities})
+ return {"files": files}
+
+
+def misplaced(data):
+ answer = read_entities(data)
+ for f in answer["files"]:
+ for e in f["entities"]:
+ for x in e["fields"]:
+ x["line"] = e["line"] # the class's line, not the field's
+ return answer
+
+
+class DdlTest(unittest.TestCase):
+ def test_tables_columns_types_keys_with_no_model(self):
+ found = {c["copybook"]: c for c in schema.tables(DDL, "db/schema.sql", contracts.stack_types(None))}
+ self.assertEqual(sorted(found), ["CUSTOMER", "ORDERS"])
+ customer = {f["name"]: f for f in found["CUSTOMER"]["records"][0]["fields"]}
+ self.assertEqual([f for f in customer], ["ID", "NAME", "CREDIT", "JOINED", "ACTIVE"]) # the PRIMARY KEY clause is a key, not a column
+ self.assertEqual((customer["NAME"]["type"], customer["NAME"]["length"], customer["NAME"]["nullable"], customer["NAME"]["line"]), ("text", 40, False, 4))
+ self.assertEqual((customer["CREDIT"]["type"], customer["CREDIT"]["digits"], customer["CREDIT"]["scale"]), ("decimal", 9, 2))
+ self.assertEqual(customer["CREDIT"]["says"], "decimal, 7 integer and 2 fraction digits")
+ self.assertEqual((customer["JOINED"]["says"], customer["ACTIVE"]["says"]), ("date", "true or false"))
+ self.assertEqual(customer["ID"]["key"], "primary")
+ orders = {f["name"]: f for f in found["ORDERS"]["records"][0]["fields"]}
+ self.assertEqual(orders["ID"]["key"], "primary")
+ self.assertEqual(orders["CUSTOMER_ID"]["key"], "foreign: CUSTOMER(ID)")
+ self.assertEqual(orders["NOTE"]["says"], "text")
+ self.assertEqual(found["ORDERS"]["how"], "SQL DDL, read with no model")
+
+ def test_the_target_stacks_types_apply_as_today(self):
+ types = contracts.stack_types(contracts.parse_stack("React; Java 21 with Spring Boot; PostgreSQL"))
+ found = {c["copybook"]: c for c in schema.tables(DDL, "db/schema.sql", types)}
+ customer = {f["name"]: f for f in found["CUSTOMER"]["records"][0]["fields"]}
+ self.assertEqual(customer["NAME"]["stack"], {"code": "String", "column": "VARCHAR(40)"})
+ self.assertEqual(customer["CREDIT"]["stack"], {"code": "BigDecimal", "column": "NUMERIC(9,2)"})
+ self.assertNotIn("stack", customer["JOINED"]) # no type table names a date: the neutral type stands
+
+
+class EntitiesTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name})
+ env.start()
+ self.addCleanup(env.stop)
+
+ def read(self, name, answer=read_entities):
+ self.folder = new_run(name.replace("-", ""))
+ self.folder.update(project="shop", tools="claude")
+ self.legacy = stacks.write(self.folder.root / "claude" / "legacy" / "shop", stacks.FIXTURES[name])
+ self.claude = FakeClaude(schema=answer)
+ self.claude.root = self.folder.root / "claude"
+ return schema.read(self.folder, self.claude, self.legacy, profile.profile_folder(self.legacy), contracts.stack_types(None))
+
+ def test_java_the_schema_and_the_entity(self):
+ found = self.read("java")
+ self.assertEqual(sorted(found["contracts"]), ["ORDER", "ORDERS"]) # the table, with no model, and the @Entity class, by the step
+ self.assertEqual(found["problems"], [])
+ entity = found["contracts"]["ORDER"]
+ self.assertEqual((entity["kind"], entity["table"], entity["file"]), ("entity", "ORDERS", "src/main/java/org/demo/shop/model/Order.java"))
+ fields = {f["name"]: f for f in entity["records"][0]["fields"]}
+ self.assertEqual((fields["customer"]["says"], fields["customer"]["line"], fields["id"]["key"]), ("text, 40 characters", 12, "primary"))
+ self.assertEqual(fields["total"]["type"], "decimal")
+ self.assertEqual([c[0] for c in self.claude.other_calls], ["schema-entities-b1"])
+ uses = schema.uses(self.legacy, found["contracts"])
+ self.assertEqual(uses["SRC/MAIN/JAVA/ORG/DEMO/SHOP/SERVICE/ORDERSERVICE.JAVA"], {"ORDER": "entity"}) # the service names the class
+ self.read_again_is_kept()
+
+ def read_again_is_kept(self):
+ before = len(self.claude.other_calls)
+ schema.read(self.folder, self.claude, self.legacy, profile.profile_folder(self.legacy), contracts.stack_types(None))
+ self.assertEqual(len(self.claude.other_calls), before) # nothing changed: no step
+
+ def test_dotnet_entities_beside_the_db_context(self):
+ found = self.read("dotnet")
+ self.assertIn("ORDER", found["contracts"])
+ fields = [f["name"] for f in found["contracts"]["ORDER"]["records"][0]["fields"]]
+ self.assertEqual(fields, ["Id", "Customer", "Quantity", "Total"])
+
+ def test_a_field_not_on_its_cited_line_is_asked_again_then_left_unread(self):
+ found = self.read("java", answer=misplaced)
+ self.assertEqual([c[0] for c in self.claude.other_calls], ["schema-entities-b1", "schema-entities-b1-retry"])
+ self.assertIn("is not on line", self.claude.other_calls[1][2])
+ self.assertEqual(sorted(found["contracts"]), ["ORDERS"]) # the table still stands; the entity is not guessed
+ self.assertTrue(any("is not on line" in p for p in found["problems"]))
+
+
+if __name__ == "__main__":
+ unittest.main()
From 97bc567fe056778c339de85ac26ad140fbb8a1b7 Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 08:26:59 -0700
Subject: [PATCH 7/8] L1-07: "runs as" for any stack
Each capability's "runs as" comes from the screens, routes and job
definitions of any stack (docs/any-legacy.md, section 5.4). The
mainframe's rule is unchanged.
- Online: the capability's rules are in code behind a screen. That is
the view, the handlers that render it, the handler its form posts to,
and the classes they use.
- Scheduled job: the code is a job definition (cron, Quartz, Spring
Batch, @Scheduled, Windows tasks, JCL), or a file one uses, or a
rule's entry cites one. Both online and a scheduled job give "online
and scheduled job", as before.
- Service: routes reach the code and no screen does.
- Library: nothing in the source shows how the code runs. The package's
API task then builds the library the rest of the application calls,
and the specification counts list it.
Tests: for each fixture (the Java web application online and its
nightly job, .NET online, the PHP form handler online, the batch-only
job), a REST service with no screens and a helper nothing runs, the
mainframe's rule as before, and the batch fixture's design round.
Prepared with AI assistance.
---
src/reframe/design/general.py | 3 +-
src/reframe/design/package.py | 2 +-
src/reframe/design/specs.py | 40 ++++++++++--
tests/design/test_no_screens.py | 1 +
tests/design/test_runs_as.py | 110 ++++++++++++++++++++++++++++++++
tests/stacks.py | 4 ++
6 files changed, 153 insertions(+), 7 deletions(-)
create mode 100644 tests/design/test_runs_as.py
diff --git a/src/reframe/design/general.py b/src/reframe/design/general.py
index d3f148e1..5709a1d3 100644
--- a/src/reframe/design/general.py
+++ b/src/reframe/design/general.py
@@ -355,7 +355,8 @@ def target_of(raw: str, where: str) -> str | None:
resolved, unresolved = settle(folder, claude, legacy, unsettled, views, table, stack, plan_only)
links += resolved
for s in screens["screens"]: # the code behind a screen: the handlers that render it and what they use
- handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table})
+ handlers = sorted({table[x["from"]]["handler"] for x in links if x["kind"] == "renders" and x["to"] == s["file"] and x["from"] in table}
+ | {table[x["to"]]["handler"] for x in links if x["kind"] == "form" and x["from"] == s["file"] and x["to"] in table})
used = sorted({f for h in handlers for f in used_files(legacy, h, stems)})
s["programs"] = [{"name": p, "file": p} for p in dict.fromkeys([s["file"], *handlers, *used])]
reached = {sid for link in links if link["kind"] != "renders" for sid in screens_of.get(link["to"], set())}
diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py
index 78823390..fb3a0ff0 100644
--- a/src/reframe/design/package.py
+++ b/src/reframe/design/package.py
@@ -175,7 +175,7 @@ def add(role: str, title: str, qs: list[dict[str, Any]], details: list[str], dep
add("business-rules", "Implement error handling and messages", by_class["error handling"] + by_class["formatting"],
["Show every message word for word; formatting rules may be restyled to the design system."], first)
shape = {"online": "the services behind the screens", "scheduled job": "the scheduled job", "online and scheduled job": "the services and the scheduled job",
- "service": "the service"}[s["runs_as"]]
+ "service": "the service", "library": "the library the rest of the application calls"}[s["runs_as"]]
notes = [f"{rid.get(n['rule'], n['rule'])}: {n['note']}" for n in s["design_notes"]]
add("api", f"Build {shape}", by_class["design note"] or (reqs if s["runs_as"] != "online" and not s["screens"] else []), notes or ["Expose the rules as the service the screens call."],
[t["id"] for t in found if t["role"] in ("data", "business-rules")])
diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py
index 20ee13b4..5773140e 100644
--- a/src/reframe/design/specs.py
+++ b/src/reframe/design/specs.py
@@ -139,13 +139,39 @@ def example_criteria(reqs: list[dict[str, Any]], rules: dict[str, Any]) -> list[
return found
-def runs_as(rules: list[dict[str, Any]], online: set[str]) -> str:
+def what_runs(legacy: Path) -> tuple[set[str], set[str]]:
+ """For any stack but the mainframe (L1-07): the source files of job definitions and of routes, each with the files it
+ uses, by path in capitals (a program's name, L1-02)."""
+ from reframe.design.general import used_files
+ from reframe.source import profile
+ stems: dict[str, list[str]] = defaultdict(list)
+ for item in legacy.rglob("*"):
+ if item.is_file():
+ stems[item.stem].append(item.relative_to(legacy).as_posix())
+ jobs: set[str] = set()
+ routes: set[str] = set()
+ for what, into in (("jobs", jobs), ("routes", routes)):
+ for rel in profile.files_with(legacy, what):
+ into |= {x.upper() for x in [rel, *used_files(legacy, rel, stems)]}
+ return jobs, routes
+
+
+def runs_as(rules: list[dict[str, Any]], online: set[str], jobs: set[str] | None = None, routes: set[str] | None = None) -> str:
"""How the capability runs in the new application: online (behind screens), as a scheduled job (from JCL), or both;
- a service when the source shows neither."""
+ a service when the source shows neither. For any stack but the mainframe (L1-07, docs/any-legacy.md section 5.4),
+ `jobs` and `routes` are the source files of job definitions and routes, with the files they use: a rule whose code
+ is one of them, or whose entry cites one, runs as a scheduled job, or as a service when no screen reaches it; a
+ library when nothing in the source shows how it runs."""
entries = [e.lower() for r in rules for e in r.get("entry") or []]
on = any("/csd/" in e or e.endswith(".csd") for e in entries) or any(str(r.get("program", "")).upper() in online for r in rules)
job = any(re.search(r"/(jcl|proc|scheduler)/|\.jcl\b|\.prc\b", e) for e in entries)
- return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service"
+ if jobs is None:
+ return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service"
+ code = {str(r.get("program", "")).upper() for r in rules} | {e.rsplit(":", 1)[0].upper() for e in entries}
+ on = on or bool(code & online)
+ job = job or bool(code & jobs)
+ served = bool(code & (routes or set()))
+ return "online and scheduled job" if on and job else "online" if on else "scheduled job" if job else "service" if served else "library"
def screens_for(key: str, codes: set[str], rule_keys: set[str], modern: dict[str, Any], journeys: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]:
@@ -206,9 +232,13 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None
signed[x["function"]].append({"reviewer": x.get("reviewer", ""), "at": x.get("at", ""), "comment": x.get("comment", "")})
online = {p["name"].upper() for s in inventory.get("screens") or [] for p in s.get("programs") or []} | \
{str(t.get("program", "")).upper() for t in flow.get("transactions") or []}
+ jobs: set[str] | None = None
+ routes: set[str] | None = None
if contracts is not None: # any stack but the mainframe (L1-06): the tables and entities each source file names
from reframe.design import schema
uses = schema.uses(legacy, contracts) if legacy and legacy.is_dir() else {}
+ if legacy and legacy.is_dir():
+ jobs, routes = what_runs(legacy)
else:
uses = data_contracts.uses(legacy) if legacy and legacy.is_dir() else {}
domain_of = {f: d for d in requirements.get("domains") or [] for f in d.get("functions") or []}
@@ -239,7 +269,7 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None
"domain_key": domain.get("key", ""), "number": cap["number"], "title": cap.get("title", ""), "story": cap.get("story", ""),
"risk": cap.get("risk", ""), "touches": cap.get("touches") or [],
"status": "final" if signed.get(page) else "draft", "signed_off": signed.get(page) or [],
- "runs_as": runs_as(mine, online),
+ "runs_as": runs_as(mine, online, jobs, routes),
"requirements": [{"key": f"{page}/{q['code']}", "code": q["code"], "kind": q.get("kind", ""), "pattern": q.get("pattern", ""), "text": q["text"],
"rules": q.get("rules") or [], "class": requirement_class([rules[k] for k in q.get("rules") or [] if k in rules])} for q in reqs],
"rules": [{"key": r["key"], "name": r.get("name", ""), "kind": r.get("kind", ""), "class": class_of(r.get("kind", "")),
@@ -526,7 +556,7 @@ def counts(specs: list[dict[str, Any]], books: dict[str, Any]) -> dict[str, Any]
"contracts": len(books), "tables": sum(len(s["tables"]) for s in specs), "gaps": sum(s["gaps"] for s in specs),
"questions": len({q["id"] or q["question"] for s in specs for q in s["questions"]}),
"classes": {c: sum(1 for s in specs for r in s["rules"] if r["class"] == c) for c in CLASS_ORDER},
- "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service")}}
+ "runs_as": {k: sum(1 for s in specs if s["runs_as"] == k) for k in ("online", "scheduled job", "online and scheduled job", "service", "library")}}
def main(argv: list[str] | None = None) -> int:
diff --git a/tests/design/test_no_screens.py b/tests/design/test_no_screens.py
index 17e4a245..6219b813 100644
--- a/tests/design/test_no_screens.py
+++ b/tests/design/test_no_screens.py
@@ -68,6 +68,7 @@ def test_specifications_golden_datasets_package_and_backlog_without_screens(self
self.assertIn("no screens", value["stages"][stage]["left_out"])
self.assertEqual([c[0].split("-")[0] for c in self.claude.other_calls], ["specs"]) # only the specifications' step
self.assertEqual(value["stages"]["specs"]["redone"][0]["name"], "Billing/Invoice")
+ self.assertEqual([s["runs_as"] for s in self.folder.load("design/specs.json")["specs"]], ["scheduled job"]) # L1-07: the batch job uses it
self.assertFalse(self.folder.path("outputs/design/prototype/index.html").exists())
self.assertIn("- Left out: the codebase has no screens.", self.folder.path("design/changes-1.md").read_text())
page = self.folder.path("outputs/design/index.html").read_text()
diff --git a/tests/design/test_runs_as.py b/tests/design/test_runs_as.py
new file mode 100644
index 00000000..2af133ad
--- /dev/null
+++ b/tests/design/test_runs_as.py
@@ -0,0 +1,110 @@
+"""L1-07: "runs as" for any stack (docs/any-legacy.md, section 5.4): online, scheduled job, service or library from the
+screens, routes and job definitions, for each fixture. The mainframe's rule is unchanged."""
+import os
+import tempfile
+import unittest
+from unittest import mock
+
+from reframe.core.runfolder import new_run
+from reframe.design import general, specs
+from reframe.source import profile
+from tests import stacks
+from tests.design.test_general import read_views
+from tests.reconcile.test_decide import FakeClaude
+
+SERVICE = { # a REST service with no screens, and a helper nothing runs
+ "src/main/java/org/demo/rates/RateResource.java": """package org.demo.rates;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+
+@Path("/rates")
+public class RateResource {
+ private final RateTable table = new RateTable();
+
+ @GET
+ public String rate() {
+ return table.current();
+ }
+}
+""",
+ "src/main/java/org/demo/rates/RateTable.java": """package org.demo.rates;
+
+public class RateTable {
+ public String current() {
+ return "4.25";
+ }
+}
+""",
+ "src/main/java/org/demo/rates/Rounding.java": """package org.demo.rates;
+
+public class Rounding {
+ public static double half(double x) {
+ return Math.round(x * 100) / 100.0;
+ }
+}
+""",
+}
+
+
+def rule(program, entry=()):
+ return {"key": f"rec/{program}", "program": program.upper(), "entry": list(entry)}
+
+
+class RunsAsTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ env = mock.patch.dict(os.environ, {"REFRAME_HOME": self.tmp.name})
+ env.start()
+ self.addCleanup(env.stop)
+
+ def context(self, files, name="fixture"):
+ """The online programs (behind the general reader's screens), and the jobs and routes, as assemble works them out."""
+ folder = new_run(name)
+ folder.update(project="x", tools="claude")
+ legacy = stacks.write(folder.root / "claude" / "legacy" / "x", files)
+ stack = profile.profile_folder(legacy)
+ folder.save(profile.FILE, stack)
+ claude = FakeClaude(reader=read_views)
+ claude.root = folder.root / "claude"
+ found = general.read_screens(folder, claude, legacy, profile.files_with(legacy, "ui"), "x")
+ general.read_flow(folder, claude, legacy, found, stack)
+ folder.save("design/screens.json", found)
+ online = {p["name"].upper() for s in found["screens"] for p in s["programs"]} # as assemble reads it from design/screens.json
+ jobs, routes = specs.what_runs(legacy)
+ return lambda *rules: specs.runs_as(list(rules), online, jobs, routes)
+
+ def test_java_web_online_and_a_scheduled_job(self):
+ runs = self.context(stacks.JAVA_WEB)
+ self.assertEqual(runs(rule("src/main/java/org/demo/shop/service/OrderService.java")), "online") # behind the order screens
+ self.assertEqual(runs(rule("src/main/java/org/demo/shop/jobs/NightlyReport.java")), "scheduled job") # @Scheduled
+ self.assertEqual(runs(rule("src/main/java/org/demo/shop/service/OrderService.java"), rule("src/main/java/org/demo/shop/jobs/NightlyReport.java")),
+ "online and scheduled job")
+
+ def test_dotnet_online(self):
+ runs = self.context(stacks.DOTNET)
+ self.assertEqual(runs(rule("Shop/Controllers/OrdersController.cs")), "online")
+
+ def test_php_the_form_handler_is_online(self):
+ runs = self.context(stacks.PHP)
+ self.assertEqual(runs(rule("orders.php")), "online") # the page's form posts to it
+
+ def test_batch_a_scheduled_job(self):
+ runs = self.context(stacks.BATCH)
+ self.assertEqual(runs(rule("src/main/java/org/demo/billing/InvoiceProcessor.java")), "scheduled job") # the batch job uses it
+ self.assertEqual(runs(rule("src/main/java/org/demo/billing/X.java", ["deploy/crontab:1"])), "scheduled job") # an entry in the crontab
+
+ def test_a_service_with_no_screens_and_a_library(self):
+ runs = self.context(SERVICE)
+ self.assertEqual(runs(rule("src/main/java/org/demo/rates/RateTable.java")), "service") # a route reaches it, no screen does
+ self.assertEqual(runs(rule("src/main/java/org/demo/rates/Rounding.java")), "library") # nothing in the source runs it
+
+ def test_the_mainframe_rule_is_unchanged(self):
+ self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": ["app/jcl/RUN.jcl:3"]}], set()), "scheduled job")
+ self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": []}], set()), "service") # no "library" on the mainframe
+ self.assertEqual(specs.runs_as([{"program": "PROG1", "entry": []}], {"PROG1"}), "online")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/stacks.py b/tests/stacks.py
index e6ba356f..b4b2fd3b 100644
--- a/tests/stacks.py
+++ b/tests/stacks.py
@@ -276,6 +276,10 @@
@EnableBatchProcessing
public class BillingJobConfig {
public static final String JOB = "monthlyBilling";
+
+ public InvoiceProcessor processor() {
+ return new InvoiceProcessor();
+ }
}
""",
"src/main/java/org/demo/billing/InvoiceProcessor.java": """package org.demo.billing;
From 7c3ce1318a24d9d431a27b0e6b2b5be579379c04 Mon Sep 17 00:00:00 2001
From: sknampally
Date: Sat, 28 Nov 2026 08:29:49 -0700
Subject: [PATCH 8/8] L1-08: words, README and docs
Reframe's words follow docs/any-legacy.md, section 6: "the legacy
source", not "the mainframe", except where they mean exactly the
mainframe.
- The tagline on the header and in `reframe --help`: "From legacy source
to reviewed requirements, business rules and a design to build from".
`reframe run`'s help and the guided run ask for the legacy source, and
say AWS Transform is for mainframe source. The published reports'
index speaks of legacy assessments.
- The package speaks of a modernized legacy application. A mainframe's
mechanics (VSAM, CICS, JCL, COMMAREA) are named as an example, not as
the only kind. START-HERE.md names the stack it was made from (for
example "Java and JSP, java"), and its data contracts are copybooks,
tables or entities.
- The README says what each family gets in one table: the tools, how
the design reads screens, flow and data, and what is proven (end to
end for the mainframe; offline for Java, .NET and PHP; not yet for
the rest). Its roadmap says release 1.1 is built and tested offline,
with live acceptance next.
- The guide has a section on what Reframe reads for each stack: the
mainframe as it is, then Java, .NET, web scripts and the rest, and a
codebase with no screens.
- docs/cli.md and the help image (docs/images/cli-help.svg, regenerated
at the same width) show the new help.
Every Markdown link and anchor in the README, the guide and the command
reference resolves.
Prepared with AI assistance.
---
README.md | 21 ++-
docs/cli.md | 4 +-
docs/guide.md | 33 ++++
docs/images/cli-help.svg | 308 ++++++++++++++++-----------------
src/reframe/core/cli.py | 6 +-
src/reframe/core/guide.py | 2 +-
src/reframe/core/ui.py | 2 +-
src/reframe/design/handover.py | 6 +-
src/reframe/design/package.py | 13 +-
src/reframe/report/pages.py | 2 +-
10 files changed, 220 insertions(+), 177 deletions(-)
diff --git a/README.md b/README.md
index 9ff021e1..a15998a6 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
From legacy source to reviewed requirements, business rules and a design to build from.
- Tested end to end on mainframe COBOL and CICS. On other languages, Claude's assessment and the reconciliation should work, untested.
+ Tested end to end on mainframe COBOL and CICS. Java, .NET and PHP are tested offline, with live runs to come.
@@ -43,10 +43,17 @@
Reframe reads a legacy codebase and tells you, in plain words a business can review, what it does. It assesses the code with Claude's [code-modernization plugin](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-modernization), and with AWS Transform as well if you have it, then checks every business rule against the source code itself. From that it designs the modern application, down to a package an AI coding tool can build from.
-| Codebase | What runs | Tested |
-|---|---|---|
-| **Mainframe:** COBOL, JCL, CICS, BMS | Everything: Claude's assessment and AWS Transform's, the reconciliation against the code, the design and the package | **Yes**, end to end on AWS's CardDemo |
-| **Other languages:** Java, .NET, PHP, Python, C and more | With Claude only, since AWS Transform writes requirements only for the mainframe. The assessment and the reconciliation should work: Claude's plugin reads any language. The design reads screens, flows and data definitions from mainframe sources only, so it stops on other codebases for now | **No.** Full support is planned ([the 1.1 specification](docs/any-legacy.md)) |
+Reframe works out what the codebase is first, its *stack profile*, and picks its tools and readers from it:
+
+| Family | Tools | How the design reads screens, flow and data | Proven |
+|---|---|---|---|
+| **Mainframe:** COBOL, PL/I, JCL, CICS, BMS, IMS | Claude's assessment and AWS Transform's, reconciled | Exact readers with no model: BMS maps, CICS transfers and definitions (CSD or resource-builder YAML), copybooks | **End to end** on AWS's CardDemo |
+| **Java:** Java, JSP, JSF, Groovy, Kotlin | Claude only: AWS Transform writes requirements only for the mainframe | The general reader: views, fields and actions by a checked Claude step; links from routes and patterns; SQL DDL with no model, entities by a checked step | Offline, on small fixtures |
+| **.NET:** C#, VB.NET, ASP.NET, Razor | Claude only | The general reader, with the MVC conventions | Offline, on small fixtures |
+| **Web scripts:** PHP, Perl, Ruby, Python, classic ASP | Claude only | The general reader | Offline, on small fixtures |
+| **Front end, native, 4GL, mixed** | Claude only | The general reader | **Not yet:** they run, unproven |
+
+A codebase with no screens (a batch system, a service or a library) gets its specifications, golden datasets, package and backlog without journeys, screens or a prototype. Live runs on two codebases beyond the mainframe come next ([the 1.1 specification](docs/any-legacy.md)).
It is for modernization teams, architects and the business people who have to say "yes, that is what the system does" before anything is rebuilt.
@@ -221,12 +228,12 @@ The figures are from live runs and are recorded in [docs/acceptance.md](docs/acc
| [How to run Reframe](docs/how-to-run.md) | One page from install to handover |
| [The guide](docs/guide.md) | Every step in detail: the guided run, Claude only, results, reviews, the reconciliation, the design, sharing and teardown |
| [Commands](docs/cli.md) | Every command, option and example |
-| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md) |
+| Specifications | [The AWS Transform assessment](docs/specification.md), [the Claude assessment](docs/pipeline-2.md), [the reconciliation](docs/pipeline-3.md), [the design](docs/pipeline-4.md), [sharing](docs/sharing.md), [release 1.0](docs/release-1.md), [any legacy codebase](docs/any-legacy.md) |
| [The plan](docs/plan.md) | Every story, with what done means and the results |
## Roadmap
-- **Beyond the mainframe (1.1):** any legacy codebase Claude's plugin reads (Java, .NET, PHP and more), with Claude only, and screens, flows and data contracts read for each stack ([the specification](docs/any-legacy.md)).
+- **Beyond the mainframe (1.1):** built and tested offline: the stack profile, Claude-only runs by family, the reconciliation in the stack's words, and screens, flows, data contracts and "runs as" read for each stack. Live acceptance on two codebases comes next ([the specification](docs/any-legacy.md)).
- **Proof at scale:** a codebase several times CardDemo's size, and a mainframe expert's own check of the audit.
- **Later:** a replacement order from the specifications, real legacy outputs under GnuCOBOL, and Claude on Amazon Bedrock, live ([docs/plan.md](docs/plan.md)).
diff --git a/docs/cli.md b/docs/cli.md
index 89dab517..d1b7ecc5 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -94,11 +94,11 @@ Every command acts on your latest run; add `--run ` for another one. The
### `reframe run`
-Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown.
+Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown.
| Option | What it does |
|---|---|
-| `--source ` | the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up |
+| `--source ` | the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked and the prerequisites are assumed to be set up |
| `--profile ` | the AWS CLI profile to sign in with (default: the one saved by the guided setup) |
| `--ref ` | for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD) |
| `--mode autonomous\|interactive` | autonomous: Reframe answers AWS and records why; interactive: answer each question with reframe answer |
diff --git a/docs/guide.md b/docs/guide.md
index 4c06d2cd..08d63a46 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -5,6 +5,7 @@ Everything about running Reframe, step by step. Start with [How to run Reframe](
- [The home screen](#the-home-screen)
- [Run an assessment: the guided way](#run-an-assessment-the-guided-way)
- [Bringing source from a mainframe](#bringing-source-from-a-mainframe)
+- [What Reframe reads for each stack](#what-reframe-reads-for-each-stack)
- [Claude only, with no AWS](#claude-only-with-no-aws)
- [If a run stops](#if-a-run-stops)
- [Results](#results)
@@ -168,6 +169,38 @@ A Git repository of the application, like CardDemo's, is the easiest source. Cod
Where the check finds something, fix the package and start a new run, or go ahead knowing what AWS Transform will leave out.
+## What Reframe reads for each stack
+
+After the snapshot, Reframe works out what the codebase is, with no model, and records it in `stack-profile.json` in the run folder:
+- its languages, by file and by line;
+- its family: the one that carries more than half the lines;
+- what it has, with the files that show it: screens, routes, jobs and data.
+
+`reframe status` shows it, and so do the reviews. `reframe run --legacy ` overrides the family. For a local source, the guided run shows the profile before it starts, and asks only when no family carries most of the code.
+
+### Mainframe
+
+As in the rest of this guide:
+- Both assessments, AWS Transform's and Claude's, reconciled.
+- The exact readers, with no model: BMS maps for the screens, CICS transfers and definitions for the flow (a CSD extract or IBM's resource-builder YAML), and copybooks for the data contracts.
+- The prompts speak of COBOL, PERFORM, CALL and copybooks.
+
+### Java, .NET, web scripts and the rest
+
+AWS Transform writes requirements only for mainframe code. So these runs are Claude only (`reframe run --tools claude`): Reframe refuses `--tools both` or `aws` before it creates anything, and the guided run does not offer AWS Transform.
+
+- **Programs** are source files, named by their path, so two `OrderService.java` files in different folders stay apart.
+- **The reconciliation** speaks of the stack's languages, and of following a call, an include, an import or an inherited method. Every cited line is still checked against the snapshot.
+- **Screens:** the general reader reads the views, pages and forms the profile found. A Claude step lists each screen's fields and actions; Reframe checks every line it cites, asks again once with the reasons, and otherwise keeps the screen with no fields.
+- **Flow:** links are read from patterns with no model: an href, a form's action, a redirect, Spring and JAX-RS route annotations, Stripes' `@UrlBinding`, the ASP.NET MVC conventions, and a script page's own path. A checked Claude step settles the rest; what fails twice stays open, on the flow page.
+- **Data contracts:** `CREATE TABLE` in SQL DDL, read with no model. Entity classes (JPA, Entity Framework) by a checked Claude step.
+- **Runs as:** online when the rules are in code behind a screen; a scheduled job when a job definition (cron, Quartz, Spring Batch, `@Scheduled`, Windows tasks) runs them; a service when only routes reach them; a library otherwise.
+- **Legacy screens** are shown as their fields and actions, citing the view's lines. The old page is not drawn.
+
+### A codebase with no screens
+
+A batch system, a service or a library gets its final specifications, golden datasets, package and backlog. The journeys, modern screens and prototype are left out, and the design page says why.
+
## Claude only, with no AWS
No AWS account, or no AWS Transform? Run Reframe with Claude only ([release 1.0](release-1.md), section 2). It needs Git, [Claude Code](https://docs.anthropic.com/en/docs/claude-code) signed in, and the code-modernization plugin, which Reframe fetches itself. Claude signs in with your Claude subscription (the default), an Anthropic API key (`--auth api-key`, with `ANTHROPIC_API_KEY` set), or Amazon Bedrock (`--auth bedrock --profile --region `, the profile used for Bedrock only, or `AWS_BEARER_TOKEN_BEDROCK`).
diff --git a/docs/images/cli-help.svg b/docs/images/cli-help.svg
index b82185c2..ad53e324 100644
--- a/docs/images/cli-help.svg
+++ b/docs/images/cli-help.svg
@@ -19,325 +19,325 @@
font-weight: 700;
}
- .terminal-4233349274-matrix {
+ .terminal-612813835-matrix {
font-family: Fira Code, monospace;
font-size: 20px;
line-height: 24.4px;
font-variant-east-asian: full-width;
}
- .terminal-4233349274-title {
+ .terminal-612813835-title {
font-size: 18px;
font-weight: bold;
font-family: arial;
}
- .terminal-4233349274-r1 { fill: #68a0b3 }
-.terminal-4233349274-r2 { fill: #c5c8c6 }
-.terminal-4233349274-r3 { fill: #398280;font-weight: bold }
-.terminal-4233349274-r4 { fill: #c5c8c6;font-weight: bold }
-.terminal-4233349274-r5 { fill: #325e5d;font-weight: bold }
-.terminal-4233349274-r6 { fill: #398280 }
-.terminal-4233349274-r7 { fill: #868887 }
+ .terminal-612813835-r1 { fill: #68a0b3 }
+.terminal-612813835-r2 { fill: #c5c8c6 }
+.terminal-612813835-r3 { fill: #398280;font-weight: bold }
+.terminal-612813835-r4 { fill: #c5c8c6;font-weight: bold }
+.terminal-612813835-r5 { fill: #325e5d;font-weight: bold }
+.terminal-612813835-r6 { fill: #398280 }
+.terminal-612813835-r7 { fill: #868887 }
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
- reframe --help
+ reframe --help
-
+
-
- ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
-││
-│REFRAME│
-│From mainframe source to reviewed requirements, business rules and a design to build from│
-│Prerequisites → Sign in → Source → AWS Transform and Claude → Review → Reconcile → Design →│
-│Share│
-││
-╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯
-
-Commands
-Command What it does
-──────────────────────────────────────────────────────────────────────────────────────────────────────────────
-reframe run Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools
-claude, no AWS): with no options, a guided run that checks and sets up everything first;
-the AWS resources stay until reframe teardown
-reframe setup Check and set up the prerequisites and the AWS sign-in, without starting a run
-reframe status The run's stage, the job's plan steps, any waiting question and the next step
-reframe events The run's event log
-reframe answer Show AWS's waiting question, or answer it
-reframe resume Continue a run that stopped; nothing with a receipt is repeated
-reframe report Build the HTML report from the run's downloads again
-reframe claude The Claude assessment: assess the same snapshot with Claude's code-modernization plugin,
-show it in the same business review, load its graph into the run's Neptune cluster, and
-compare it with AWS Transform's results
-reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude
-only, every rule) against the source code, with evidence Reframe checks, then write
-recommended requirements, one SME list and the reconciliation page; needs the run's
-assessments done, and no AWS resources
-reframe review Read the review downloads in a folder and show each reviewer's coverage, sign-offs and
-where reviewers disagree; runs nothing, and the next reframe reconcile --context with
-the same folder combines them
-reframe export Write a run's reconciled results as one Excel workbook: domains, functions,
-capabilities, requirements, business rules, decision tables, open questions and the SME
-list, with the reviewers' marks; runs nothing
-reframe design The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,
-final specifications and the AI-DLC package, from the reconciled results; a round redoes
-only what new context touches
-reframe compare Build the page comparing AWS Transform's and Claude's results again
-reframe publish Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder
-others can open, upload the run's source, results and reports to your account's private
-bucket, or publish the copy to a GitHub Pages site
-reframe reports The reports published to your AWS account: list them, open one with your AWS sign-in, or
-remove the bucket
-reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them
-
-Examples
-reframe the home screen: your runs, the next step and a menu
-reframe run a guided run: checks the prerequisites, the AWS
-sign-in and the source, then starts
-reframe run --source <folder | file.zip | github-url>start straight away, with no questions
-reframe run --tools claude --source <source> Claude only: no AWS account, nothing to tear down
-reframe status where the latest run is, and what to do next
-reframe answer AWS's waiting question, in interactive mode
-reframe report --open open the business review in the browser
-reframe claude the Claude assessment: the same snapshot, assessed
-with Claude as well
-reframe compare --open open the page comparing AWS Transform and Claude
-reframe export --to xlsx the reconciled requirements and business rules as an
-Excel workbook
-reframe design --open the design: screens, journeys, the prototype, final
-specifications and the AI-DLC package
-reframe publish --to aws upload the run's source, results and cleaned reports
-to your account's private bucket
-reframe reports list the published reports; reframe reports open
-<project> opens the latest
-reframe teardown remove the AWS resources the run created
-
-Options
---version show program's version number and exit
--h, --help this help
-reframe <command> --help shows a command's options.
+
+ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
+││
+│REFRAME│
+│From legacy source to reviewed requirements, business rules and a design to build from│
+│Prerequisites → Sign in → Source → AWS Transform and Claude → Review → Reconcile → Design →│
+│Share│
+││
+╰───────────────────────────── AWS Transform · Claude · Reconciliation · Design ─────────────────────────────╯
+
+Commands
+Command What it does
+──────────────────────────────────────────────────────────────────────────────────────────────────────────────
+reframe run Assess legacy source with Claude, and mainframe source with AWS Transform beside it
+(--tools claude: Claude only, no AWS): with no options, a guided run that checks and
+sets up everything first; the AWS resources stay until reframe teardown
+reframe setup Check and set up the prerequisites and the AWS sign-in, without starting a run
+reframe status The run's stage, the job's plan steps, any waiting question and the next step
+reframe events The run's event log
+reframe answer Show AWS's waiting question, or answer it
+reframe resume Continue a run that stopped; nothing with a receipt is repeated
+reframe report Build the HTML report from the run's downloads again
+reframe claude The Claude assessment: assess the same snapshot with Claude's code-modernization plugin,
+show it in the same business review, load its graph into the run's Neptune cluster, and
+compare it with AWS Transform's results
+reframe reconcileThe reconciliation: decide every rule the two assessments do not agree on (with Claude
+only, every rule) against the source code, with evidence Reframe checks, then write
+recommended requirements, one SME list and the reconciliation page; needs the run's
+assessments done, and no AWS resources
+reframe review Read the review downloads in a folder and show each reviewer's coverage, sign-offs and
+where reviewers disagree; runs nothing, and the next reframe reconcile --context with
+the same folder combines them
+reframe export Write a run's results for other tools: the reconciled results as one Excel workbook
+(xlsx), or the design's capabilities as a backlog to import into Jira or Azure DevOps,
+with acceptance criteria; runs nothing
+reframe design The design (pipeline 4): legacy and modern screens, journeys, the clickable prototype,
+final specifications and the AI-DLC package, from the reconciled results; a round redoes
+only what new context touches
+reframe compare Build the page comparing AWS Transform's and Claude's results again
+reframe publish Optional: copy a run's reports, cleaned of the AWS account's identifiers, into a folder
+others can open, upload the run's source, results and reports to your account's private
+bucket, or publish the copy to a GitHub Pages site
+reframe reports The reports published to your AWS account: list them, open one with your AWS sign-in, or
+remove the bucket
+reframe teardown List every AWS resource the run created, ask for consent, record it, then remove them
+
+Examples
+reframe the home screen: your runs, the next step and a menu
+reframe run a guided run: checks the prerequisites, the AWS
+sign-in and the source, then starts
+reframe run --source <folder | file.zip | github-url>start straight away, with no questions
+reframe run --tools claude --source <source> Claude only: no AWS account, nothing to tear down
+reframe status where the latest run is, and what to do next
+reframe answer AWS's waiting question, in interactive mode
+reframe report --open open the business review in the browser
+reframe claude the Claude assessment: the same snapshot, assessed
+with Claude as well
+reframe compare --open open the page comparing AWS Transform and Claude
+reframe export --to xlsx the reconciled requirements and business rules as an
+Excel workbook
+reframe design --open the design: screens, journeys, the prototype, final
+specifications and the AI-DLC package
+reframe publish --to aws upload the run's source, results and cleaned reports
+to your account's private bucket
+reframe reports list the published reports; reframe reports open
+<project> opens the latest
+reframe teardown remove the AWS resources the run created
+
+Options
+--version show program's version number and exit
+-h, --help this help
+reframe <command> --help shows a command's options.
diff --git a/src/reframe/core/cli.py b/src/reframe/core/cli.py
index fac2d2a0..8c35d140 100644
--- a/src/reframe/core/cli.py
+++ b/src/reframe/core/cli.py
@@ -43,16 +43,16 @@ def _run_option(parser: argparse.ArgumentParser) -> None:
def parser() -> argparse.ArgumentParser:
from reframe.core.helptext import Parser
- top = Parser(prog="reframe", description="Run an AWS Transform mainframe assessment end to end and bring back its requirements.")
+ top = Parser(prog="reframe", description="From legacy source to reviewed requirements, business rules and a design to build from: with Claude, and for mainframe code with AWS Transform beside it.")
top.add_argument("--version", action="version", version=f"reframe {__version__}")
commands = top.add_subparsers(dest="command", metavar="")
def command(name: str, help: str) -> argparse.ArgumentParser:
return commands.add_parser(name, help=help, description=help)
- run = command("run", "Assess mainframe source with AWS Transform and Claude, or with Claude only (--tools claude, no AWS): with no "
+ run = command("run", "Assess legacy source with Claude, and mainframe source with AWS Transform beside it (--tools claude: Claude only, no AWS): with no "
"options, a guided run that checks and sets up everything first; the AWS resources stay until reframe teardown")
- run.add_argument("--source", help="the mainframe source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked "
+ run.add_argument("--source", help="the legacy source: a local folder, a local .zip file, or a GitHub URL; given, nothing is asked "
"and the prerequisites are assumed to be set up")
run.add_argument("--profile", help="the AWS CLI profile to sign in with (default: the one saved by the guided setup)")
run.add_argument("--ref", help="for a Git checkout or URL: the branch, tag or commit to assess (default: HEAD)")
diff --git a/src/reframe/core/guide.py b/src/reframe/core/guide.py
index db18d625..267ca206 100644
--- a/src/reframe/core/guide.py
+++ b/src/reframe/core/guide.py
@@ -184,7 +184,7 @@ def _reachable(url: str) -> str | None:
def source() -> tuple[str, str | None] | None:
from reframe.source.snapshot import URL
ui.section("3 Source")
- form = ui.choose("Where is the mainframe source?", [("A GitHub or Git URL", "https://github.com//"),
+ form = ui.choose("Where is the legacy source?", [("A GitHub or Git URL", "https://github.com//"),
("A local folder", "a Git checkout or a plain folder"),
("A local ZIP file", "")], setup.load_config().get("source_form") or 1)
if form == 1:
diff --git a/src/reframe/core/ui.py b/src/reframe/core/ui.py
index d1a81bd8..15adc2c6 100644
--- a/src/reframe/core/ui.py
+++ b/src/reframe/core/ui.py
@@ -24,7 +24,7 @@
def header(subtitle: str = "AWS Transform · Claude · Reconciliation · Design") -> None:
content = Text("REFRAME\n", style="bold bright_cyan")
- content.append("From mainframe source to reviewed requirements, business rules and a design to build from\n", style="bold white")
+ content.append("From legacy source to reviewed requirements, business rules and a design to build from\n", style="bold white")
content.append(STEPS, style="dim")
console.print(Panel(content, border_style="cyan", padding=(1, 2), subtitle=subtitle))
diff --git a/src/reframe/design/handover.py b/src/reframe/design/handover.py
index 7841f570..2e026f21 100644
--- a/src/reframe/design/handover.py
+++ b/src/reframe/design/handover.py
@@ -147,7 +147,7 @@ def facts(specs: list[dict[str, Any]], journeys: list[dict[str, Any]], programs:
}
-def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, form: str | None) -> str:
+def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, form: str | None, legacy: str = "") -> str:
where = WHERE[form] if form else "\n\n".join(f"**{k}**\n\n{v}" for k, v in WHERE.items()) + "\n"
drafts = "\n".join(f" - {name}: {n} draft" for name, n in sorted(f["drafts"].items())) or " - None."
proof = "\n".join(f" - {p['id']} {p['title']} ({p['criteria']} acceptance criteria; {p['status']}"
@@ -155,11 +155,11 @@ def start_here(f: dict[str, Any], project: str, stack: dict[str, Any] | None, fo
artifacts = ", ".join(f["artifacts"]) or "none"
return f"""# Start here
-This package was written by Reframe from {project}'s legacy source, its reconciled requirements and rules, and the reviewers' sign-offs. It holds what
+This package was written by Reframe from {project}'s legacy source{" (" + legacy + ")" if legacy else ""}, its reconciled requirements and rules, and the reviewers' sign-offs. It holds what
those settle. What only your team can give is marked `[FILL IN: ...]`. These steps make it ready for forward engineering.
{where}
-- Every form: `data-contracts.md` (the copybooks as typed records), `traceability.md` (every ID back to the legacy source) and `golden/`
+- Every form: `data-contracts.md` (the copybooks, tables or entities as typed records), `traceability.md` (every ID back to the legacy source) and `golden/`
(each capability's golden dataset, the cases the new system must answer as the legacy one does, and `compare.py`).
## 1. Copy the package
diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py
index fb3a0ff0..11819008 100644
--- a/src/reframe/design/package.py
+++ b/src/reframe/design/package.py
@@ -65,7 +65,7 @@
"Use synthetic data only; never copy production or personal data.",
"Keep the copybook and field names in a comment or mapping, so the legacy data can be migrated and compared."]),
"api": ("API", "Builds the services and scheduled jobs the capability runs as, from the design notes.",
- ["Follow each design note; the mainframe mechanics (VSAM, CICS, JCL, COMMAREA) are not to be copied.",
+ ["Follow each design note; the legacy platform's mechanics (on a mainframe: VSAM, CICS, JCL, COMMAREA) are not to be copied.",
"A capability that runs as a scheduled job becomes a job with the same inputs, outputs and failure handling.",
"Name the rules and requirements each endpoint or job implements."]),
"test-generation": ("Test generation", "Writes an automated test for every acceptance criterion, named by its ID.",
@@ -393,7 +393,7 @@ def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
def role_md(role: str) -> str:
name, what, rules = ROLES[role]
- return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized mainframe application.",
+ return "\n".join(["---", f"name: {role}", f"description: {what}", "---", "", f"You are the {name.lower()} role in the forward build of a modernized legacy application.",
"", what, "", "## Template", "", "For each task you take: read the task's requirements, rules and criteria by ID in the specification; "
"do the work; name the IDs you implemented; list what you could not do and why.", "", "## Guardrails", ""]
+ [f"- {r}" for r in rules] + ["- The legacy source is read-only. Use synthetic data only.", "- A draft capability is confirmed with the owner before it is built.", ""]
@@ -474,11 +474,11 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
tech = "# Tech\n\n## Target stack\n\n" + stack_md(stack, context.get("architecture", "")) + "\n"
files: dict[str, str] = {}
known = handover.facts(specs, journeys, programs or {})
- files["START-HERE.md"] = handover.start_here(known, project, stack, None)
+ files["START-HERE.md"] = handover.start_here(known, project, stack, None, context.get("legacy", ""))
kept = [d for d in datasets.values() if d["cases"] or d["uncovered"]]
comparer = Path(golden_compare.__file__).read_text()
for form in FORMS:
- files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form)
+ files[f"{form}/START-HERE.md"] = handover.start_here(known, project, stack, form, context.get("legacy", ""))
files[f"{form}/data-contracts.md"] = contracts
files[f"{form}/traceability.md"] = trace
files[f"{form}/golden/README.md"] = golden.readme(kept)
@@ -664,7 +664,10 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
root = Path(tmp) / "package"
inventory = (folder.load("design/screens.json") or {}).get("screens") or []
programs = {s["map"]: [p["name"] for p in s.get("programs") or []] for s in inventory}
- ts = write(root, specs, books, stack, journeys, prototype, project, read_context(context), programs)
+ from reframe.source import profile
+ stack_profile = profile.of_run(folder) # START-HERE names the stack (docs/any-legacy.md, section 5.5)
+ told = {**read_context(context), "legacy": f"{stack_profile['words']['languages']}, {stack_profile.get('family', 'mainframe')}"}
+ ts = write(root, specs, books, stack, journeys, prototype, project, told, programs)
problems = check(root, specs, ts)
made = manifest(specs, ts, stack)
same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root)
diff --git a/src/reframe/report/pages.py b/src/reframe/report/pages.py
index 11fbe75f..d19af073 100644
--- a/src/reframe/report/pages.py
+++ b/src/reframe/report/pages.py
@@ -122,5 +122,5 @@ def index(site: Path, pattern: str = "*/*/manifest.json", title: str = "Reframe
"main{max-width:900px;margin:0 auto;padding:32px 24px}.muted{color:var(--muted)}"
".card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px 18px;margin-bottom:12px;"
"text-decoration:none;color:var(--ink)}.card:hover{border-color:var(--accent)}.card h2{margin:0 0 4px;font-size:18px}.card p{margin:0;color:var(--muted)}"
- "
" + html.escape(title) + "
Mainframe assessments published by Reframe, cleaned of the "
+ "
" + html.escape(title) + "
Legacy assessments published by Reframe, cleaned of the "
"identifiers of the accounts that ran them. Each is model output, for people to review.