From 1fd3c82439da84cb8da7c94cb17abadadc56f656 Mon Sep 17 00:00:00 2001 From: sknampally Date: Sat, 28 Nov 2026 20:25:38 -0700 Subject: [PATCH] P4-07, P4-08, P4-11, L1-06: the forward-engineering review's fixes (#393, #394, #421, #478) One commit for the four stories the review of 28 November reopened: they change the same classes and the same files. P4-07 (#393), the final specifications: - Rules only about the old screen's mechanics (a refused key, cursor placement, a paging or exit key, session plumbing) are classed legacy interaction from their words, with no model. They get no acceptance criterion and are listed for the UI migration; a business rule that only mentions a key keeps its criteria, each with a note naming what the modern screen replaces. Technical rules stay design notes. - An example's WHEN is its event ("the sign-on processes these inputs"), never the rule's condition a counter-example does not meet; a double WHEN reads as one. - A journey screen with nothing of the capability is named as context, without an empty component table. The model step still reads every screen title, so saved answers fit and no round is redone for it. P4-08 (#394) and L1-06 (#478), the package: - Every capability gets its service or job task; a job beside the screens names its legacy programs. - SQL tables and ORM entities are stored records, with their columns in each specification, as file records are. - The copy for the team keeps the application's own e-mail addresses and IDs; anything published is still cleaned of both. - The UI and test roles say how to treat legacy interaction and unchecked golden cases. P4-11 (#421), golden datasets: - Values an outcome states are read with no model and compared by value. - An unchecked case is never a pass: compare.py reports what was verified and exits 2 until --allow-unchecked says the team's tests assert it. Checked on a copy of the JPetStore run, rebuilt with no model: 67 tables rendered with their columns, no empty component table, 14 screens as context, every package check passing, 54 of 123 golden cases checkable. Prepared with AI assistance. --- CHANGELOG.md | 7 ++ docs/any-legacy.md | 2 + docs/pipeline-4.md | 16 +++ docs/plan.md | 8 +- src/reframe/design/golden.py | 46 ++++++- src/reframe/design/golden_compare.py | 25 +++- src/reframe/design/package.py | 54 +++++--- src/reframe/design/specs.py | 101 ++++++++++++--- src/reframe/report/backlog.py | 3 +- src/reframe/report/publish.py | 23 ++-- tests/design/test_golden.py | 6 +- tests/design/test_package.py | 2 +- tests/design/test_review_fixes.py | 179 +++++++++++++++++++++++++++ tests/design/test_specs.py | 2 +- tests/report/test_backlog.py | 2 +- 15 files changed, 421 insertions(+), 55 deletions(-) create mode 100644 tests/design/test_review_fixes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 79eb2f82..512d3514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ What changed in each release. Releases are tagged on `main`; the stories behind each are in [docs/plan.md](docs/plan.md). +## Unreleased + +**After the forward-engineering review (28 November 2026)** +- Specifications: rules only about the old screen's mechanics are *legacy interaction*, with no acceptance criterion; an example's criterion states its event, not the rule's condition; a journey's screen with nothing of the capability is named as context, not given an empty table (#393). +- The package: every capability has its service or job task; SQL tables and ORM entities are stored records, rendered with their columns; the copy for the team keeps the application's own e-mail addresses and IDs (#394, #478). +- Golden datasets: values an outcome states are compared by value; an unchecked case is never a pass, and `compare.py` exits 2 until the team asserts it (#421). + ## 1.0.0 (27 November 2026) The first release for anyone to try: with Claude only, or with Claude and AWS Transform. Tested end to end on mainframe code; open source under the MIT License, at github.com/CodeStrata/reframe. diff --git a/docs/any-legacy.md b/docs/any-legacy.md index 6f016fd6..54a22bd5 100644 --- a/docs/any-legacy.md +++ b/docs/any-legacy.md @@ -100,6 +100,8 @@ The profile is shown by `reframe status`, carried into the reports' About sectio **Journeys, modern screens and the prototype** work from the screens and flow the reader gives them, whatever made them. The modern screen mapping maps legacy fields, whether a BMS field or a form input. +**After review (28 November 2026, #478):** an SQL table and an ORM entity are stored records, like a mainframe file record: rendered with their columns in each specification and named by the data task, not listed as working storage. + ### 5.5 What follows the design (L1-08) - The package, golden datasets, backlog and reports change only their words: "the legacy source", not "the mainframe". START-HERE names the stack. diff --git a/docs/pipeline-4.md b/docs/pipeline-4.md index 93912216..91c856c9 100644 --- a/docs/pipeline-4.md +++ b/docs/pipeline-4.md @@ -192,6 +192,11 @@ A capability in a signed-off function is **final**; every other one is **draft** - **40 data contracts**, 113 decision tables with 82 gaps, 485 open SME questions. - **Checks:** every citation exists, every requirement has a criterion and every technical rule a note; nothing failed. The page is 3.1 MB. +**After the forward-engineering review (28 November 2026, #393).** Three changes, all with no model: +- **Legacy interaction.** A rule only about the old screen's mechanics (a key the screen refuses, cursor placement, a paging or exit key, session plumbing such as `COMMAREA` or a first entry) is classed *legacy interaction*, read from its words. It gets no acceptance criterion, since the modern screen replaces it. Each specification lists it under *Legacy interaction to replace*, and the first screen task carries it. A business rule that only mentions a key or a typed Y or N keeps its criteria, each with a note naming what the modern screen replaces. A technical rule stays a design note. On CardDemo's published specifications the patterns pick about 140 of 1,185 rules; restating the business intent of the rest in channel-neutral words is for a later round with the model. +- **One event per worked example.** An example's criterion no longer restates the rule's condition, which a counter-example does not meet: its WHEN is the event ("the sign-on processes these inputs"), and the GIVEN holds the case. A trigger written as two WHENs reads as one ("x and y"). An event written by the model for each example is for a later round. +- **Screens.** A journey's screen with nothing of the capability is named as context, without an empty component table. The model step still reads every screen of the journeys, so a saved answer still fits and a round redoes nothing for this. + ### D7 Package (P4-08) Written by Reframe from D6, in `outputs/design/package/v/`, in three forms: @@ -220,6 +225,12 @@ Every requirement, rule, acceptance criterion and task keeps its ID, so the forw **On CardDemo** (26 November 2026), in 2 seconds: 1,113 files, 13 MB with the prototype. The 154 capabilities (52 final) have 820 tasks: 222 business rules, 118 data, 114 API, 99 UI modernization, 154 test generation and 113 compliance. No check failed. A cleaned copy left nothing behind. A copy has 85 placeholders in 18 files and 102 draft capabilities left; the *Sign in* slice is USPM-C01 *Sign on to CardDemo*, 19 criteria, still draft. +**After the forward-engineering review (28 November 2026, #394).** +- **Every capability gets its service or job task:** built from the design notes, else from its requirements. A capability that runs online and as a scheduled job names the job's legacy programs. +- **Stored records:** a file record, an SQL table and an ORM entity are all data the capability keeps. They are rendered with their columns in each specification, and the data task names them (L1-06, #478). +- **The copy for the team** (`reframe design --package`) is cleaned of the account, ARNs, S3 locations, the AWS profile, the run's resources, local paths and API keys, but keeps the application's own e-mail addresses and IDs, such as a sample address in a rule or a golden case's input. Anything published is still cleaned of both. +- **Role guardrails:** the UI role builds the modern equivalent of legacy interaction, never the key. The test role treats a criterion's legacy note as the behaviour to replace, and never treats an unchecked golden case as a pass. + ### D8 Design page (P4-07, P4-10) `outputs/design/index.html`, in the review layout: overview first (screens, journeys, mapping counts, final and draft capabilities); then the flow map, each journey with its screens side by side (legacy and modern), the mapping table with filters, and each capability's specification. The reconciliation page links to it, and `reframe publish` includes it with the prototype. @@ -278,6 +289,11 @@ Comparisons are exact for money, dates, status codes, IDs and counts, and a diff **On CardDemo** (run fa1f61, from its 154 specifications, with no model, 26 November 2026): 1,595 cases for 139 capabilities, 633 of them for final capabilities. 1,000 come from worked examples and 595 from decision-table rows; 746 are edge cases, and 900 quote a message or code. 82 combinations are left uncovered for the owner. The cases run against 1,186 screens, 292 jobs and 117 services. The package grew to 1,536 files, and no check failed. The other 15 capabilities have only design notes, so they have no cases. +**After the forward-engineering review (28 November 2026, #421).** +- **Expected values.** An outcome that states a value ("the declined total is 110.00", "(OUT-ACCT-CURR-CYC-DEBIT) is 2525.00", "the account total resets to 0") gives the case that value, with its kind, compared by value. This is read with no model: on CardDemo's published criteria it finds values in about 70 of 1,654, and on JPetStore 4 of its 123 cases have values and 51 have messages. Structured expected values written by the reconciliation's decision step, for every worked example, need a live round and are the next step. +- **Unchecked is never a pass.** A case with nothing to compare is *unchecked*. `compare.py` reports how many cases were verified, and exits 2 when nothing differs but some cases were unchecked, until `--allow-unchecked` says the team's own tests assert them. +- **Legacy interaction has no cases**, like a design note. + ### D11 Risk and replacement order (P4-12) Each capability already has a risk (P3-24) and touches a list of things (money, card data, personal data, security, audit, record updates, reporting only). Reframe orders the capabilities for replacement: low risk and read-only first (reporting, inquiry screens), then updates, and money, security and adjudication last. Within that order, a capability that shares data stores or screens with another follows it. The order is shown on the design page and written into the package's constitution and tasks, each with its reason. diff --git a/docs/plan.md b/docs/plan.md index eb011298..2e96677f 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -171,11 +171,11 @@ Agreed by the owner on 24 November 2026. From the reconciled and reviewed result | P4-04 | User journeys | [§4 D3](pipeline-4.md) | Done 25 November 2026: screens are grouped into the tasks people do, each journey linked to its capabilities and requirements; on CardDemo 20 journeys over all 21 screens, every answer passing Reframe's checks | | P4-05 | Modernized screens and their mapping | [§4 D4, §5](pipeline-4.md) | Done 25 November 2026 (#420), and proven in P4-10's live rounds: each journey has modern screen designs. A mapping table takes every legacy screen and field to its new component as kept, merged, dropped or new, with the reason; no legacy field is left unmapped. Each screen also records its role, data and service dependencies, the pain points it removes and test scenarios, and follows a `style-reference/` folder where the design system is silent | | P4-06 | The clickable prototype | [§4 D5](pipeline-4.md) | Done 25 November 2026: one static HTML app with a route per screen, sample data shaped by the fields and messages written from the rules, each screen beside the legacy screens it replaces; screens and components can be marked *Agree*, *Needs change* or *Question*, journeys signed off, and the marks downloaded | -| P4-07 | Final specifications | [§4 D6, D8](pipeline-4.md) | Done 26 November 2026: per capability, the final requirements and business rules, screen specifications, data contracts from the copybooks, acceptance criteria, decision tables with their gaps, and the questions still open, each citing its sources; each rule and requirement classed as business rule, formatting, error handling, side effect or historical artifact | -| P4-08 | The AI-DLC package | [§4 D7](pipeline-4.md) | Done 26 November 2026, with placeholders and START-HERE.md for what the engineer gives (the stack, house conventions, skills); the *Sign in* build check is the engineer's step (owner's decision). One package in three forms: Kiro (`.kiro/specs//` with `requirements.md`, `design.md` and `tasks.md`, and steering files), Claude Code (`CLAUDE.md`, the specifications, the prototype as the UI reference and the tasks) and Spec Kit (a constitution, `specs//` and role files under `.claude/agents/`, each task naming its role), every item keeping its requirement and rule IDs. Checked by loading it into Claude Code and building one journey | +| P4-07 | Final specifications | [§4 D6, D8](pipeline-4.md) | Done 26 November 2026: per capability, the final requirements and business rules, screen specifications, data contracts from the copybooks, acceptance criteria, decision tables with their gaps, and the questions still open, each citing its sources; each rule and requirement classed as business rule, formatting, error handling, side effect or historical artifact. Reworked 28 November 2026 after the forward-engineering review (#393): legacy interaction is its own class with no acceptance criterion, an example's WHEN is its event, and context screens have no empty table | +| P4-08 | The AI-DLC package | [§4 D7](pipeline-4.md) | Done 26 November 2026, with placeholders and START-HERE.md for what the engineer gives (the stack, house conventions, skills); the *Sign in* build check is the engineer's step (owner's decision). One package in three forms: Kiro (`.kiro/specs//` with `requirements.md`, `design.md` and `tasks.md`, and steering files), Claude Code (`CLAUDE.md`, the specifications, the prototype as the UI reference and the tasks) and Spec Kit (a constitution, `specs//` and role files under `.claude/agents/`, each task naming its role), every item keeping its requirement and rule IDs. Checked by loading it into Claude Code and building one journey. Reworked 28 November 2026 after the review (#394): every capability has its service or job task, tables and entities are stored records, and the copy for the team keeps the application's own e-mail addresses and IDs | | P4-09 | Rounds with more context | [§4 D9](pipeline-4.md) | Done 26 November 2026 (`python -m reframe.design.pipeline`, with `--plan`): added context redoes only the parts it touches; each round versions the package and writes what changed since the last | | P4-10 | Live acceptance and README | [§8](pipeline-4.md) | Done 26 November 2026 ([results](pipeline-4.md)): rounds 1 and 2 on CardDemo from the CLI; round 2's persona, design system and *Needs change* redid only what they reach, and a kept part now records its pieces so a later round can say why. On CardDemo, from the CLI: the prototype covers every screen, a second round with added context changes only what it should, and the README and `docs/cli.md` describe pipeline 4 from the tested commands | -| P4-11 | Golden datasets and equivalence tests | [§4 D10](pipeline-4.md) | #421 · Done 26 November 2026 (#456; the owner moved it forward from Later, the same day), with no model: per capability, a golden dataset from the worked examples and decision tables in each form of the package, with `golden/compare.py` setting formatting apart from business differences, and the test-generation task naming every case. On CardDemo: 1,595 cases for 139 capabilities, 746 edge cases and 82 combinations left for the owner. Expected outputs come from the rules until P4-13 | +| P4-11 | Golden datasets and equivalence tests | [§4 D10](pipeline-4.md) | #421 · Done 26 November 2026 (#456; the owner moved it forward from Later, the same day), with no model: per capability, a golden dataset from the worked examples and decision tables in each form of the package, with `golden/compare.py` setting formatting apart from business differences, and the test-generation task naming every case. On CardDemo: 1,595 cases for 139 capabilities, 746 edge cases and 82 combinations left for the owner. Expected outputs come from the rules until P4-13. Reworked 28 November 2026 after the review (#421): values an outcome states are compared by value, and an unchecked case is never a pass (`compare.py` exits 2) | | P4-12 | Risk and replacement order | [§4 D11](pipeline-4.md) | **Later** (the owner, 26 November 2026). Capabilities are ordered for replacement from their risk and what they touch, low-risk and read-only first and money, security and adjudication last, shared data and screens kept together; the order and its reasons are on the design page and in the package's constitution and tasks | | P4-13 | Spike: real legacy outputs under GnuCOBOL (low priority) | [§4 D12](pipeline-4.md) | #423 · Spike written 28 November 2026 ([spikes/p4-13-gnucobol.md](spikes/p4-13-gnucobol.md)), for the owner: 10 of CardDemo's 12 batch programs compile under GnuCOBOL 3.1.2 in a container and 8 run to a normal end on CardDemo's own data. The reconciled rules for posting and interest agree with the real outputs (300 of 300 reject decisions, 50 of 50 interest amounts), but only when amounts are truncated to the cent, which the interest rule does not say. The real run also shows that one recommended rule is wrong: the interest batch never posts the last account's interest, a CardDemo defect. Proposed: a story for an optional legacy run in the golden datasets | @@ -223,7 +223,7 @@ The owner's direction (27 November 2026): Reframe takes any legacy codebase Clau | L1-03 | A reconciliation in the stack's words | [§5.3](any-legacy.md) | #475 · The prompts and source files come from the profile; the evidence check, the audit and the expert's pack work on a non-mainframe fixture | | L1-04 | A design without screens | [§5.4](any-legacy.md) | #476 · A batch or service fixture gets its specifications, golden datasets, package and backlog, with journeys, screens and the prototype left out and the page saying why | | L1-05 | Screens and flow from any stack | [§5.4](any-legacy.md) | #477 · The general reader lists each view's fields and actions and the routes and links between them, each citing lines and checked; patterns that settle a link need no model; what fails twice is unresolved | -| L1-06 | Data contracts from any stack | [§5.4](any-legacy.md) | #478 · SQL DDL is read with no model; entity classes by a checked model step; the target stack's types apply as today | +| L1-06 | Data contracts from any stack | [§5.4](any-legacy.md) | #478 · SQL DDL is read with no model; entity classes by a checked model step; the target stack's types apply as today. Reworked 28 November 2026 after the review (#478): tables and entities are stored records in the package | | L1-07 | "Runs as" for any stack | [§5.4](any-legacy.md) | #479 · Online, scheduled job, service or library from screens, routes and job definitions, for each fixture | | L1-08 | Words, README and docs | [§5.5, 6](any-legacy.md) | #480 · The tagline, the README's table by family, the guide and every stage's words follow section 6 | | L1-09 | Live acceptance on two codebases | [§7](any-legacy.md) | #481 · Section 7's *done when* on eShopModernizing and JPetStore 6, run locally, nothing committed, the results recorded here | diff --git a/src/reframe/design/golden.py b/src/reframe/design/golden.py index dfc8a8d5..ac3f0a01 100644 --- a/src/reframe/design/golden.py +++ b/src/reframe/design/golden.py @@ -52,6 +52,43 @@ def literals(text: str) -> list[str]: return list(dict.fromkeys(f for f in found if f.strip())) +NUMBER = r"[-+]?\$?\d[\d,]*(?:\.\d+)?|\d{4}-\d{2}-\d{2}" +VERB = r"(?:is|are|becomes|equals|=|is set to|is reset to|resets to|is now|stays|remains)\s+(?:the (?:number|value|amount) )?" +# a field the code names (OUT-ACCT-CURR-CYC-DEBIT, in brackets or backticks or bare), then a verb and a number or date +CODE_VALUE = re.compile(rf"[(`]?\b(?P[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)\b[)`]?\s+{VERB}(?P{NUMBER})(?![\w-])") +# a field named in words (the declined total), then a verb and a number or date +WORD_VALUE = re.compile(rf"\b(?P[A-Za-z][a-z0-9'-]*(?: [a-z][a-z0-9'-]*){{0,4}})\s+{VERB}(?P{NUMBER})(?![\w-])") +NOT_A_FIELD = {"there", "it", "this", "that", "which", "who", "result", "answer", "outcome", "value", "number", "and", "or"} + + +def value_kind(field: str, value: str) -> str: + if re.fullmatch(r"[-+]?\$?\d[\d,]*\.\d{2}", value): + return "money" # an amount with cents is money, whatever its field is called + kind = kind_of(field, value) + if kind != "text": + return kind + return "count" if re.fullmatch(r"\d+", value) else "text" + + +def expected_values(outcome: str) -> list[dict[str, str]]: + """The values an outcome states in so many words ("the declined total is 110.00", "(OUT-ACCT-CURR-CYC-DEBIT) is + 2525.00"), each with its kind, which the new system must give by value. Read with no model; an outcome that states + none gives none, and its case is then checked by its quoted messages, or by the team's own test.""" + found: dict[str, dict[str, str]] = {} + for rx in (CODE_VALUE, WORD_VALUE): + for m in rx.finditer(outcome or ""): + field = m.group("field").strip() + words = field.split() + while words and words[0].lower() in ("and", "or", "then", "so", "the", "its", "each", "a", "an", "with"): + words = words[1:] + field = " ".join(words) + if not field or field.lower() in NOT_A_FIELD or field in found: + continue + value = m.group("value").rstrip(".,") + found[field] = {"field": field, "value": value, "kind": value_kind(field, value)} + return list(found.values()) + + def target(s: dict[str, Any], rule: dict[str, Any] | None) -> dict[str, Any]: """What a case is run against: the modern screens whose components cite the rule (online), else every screen of the capability; the legacy program's job (a scheduled job); or the capability's service.""" @@ -78,15 +115,15 @@ def dataset(s: dict[str, Any]) -> dict[str, Any]: def add(rule: dict[str, Any], source: str, given: list[tuple[str, str]], outcome: str, criteria: list[str], edge: bool) -> None: cases.append({"id": f"{s['id']}-GD-{len(cases) + 1:02d}", "capability": s["id"], "rule": s["rule_ids"].get(rule["key"], rule["key"]), "rule_class": rule.get("class", ""), "from": source, "program": rule.get("program", ""), "source": list(rule.get("evidence") or []), - "input": _fields(given), "expected": {"outcome": outcome, "literals": literals(outcome), "values": []}, + "input": _fields(given), "expected": {"outcome": outcome, "literals": literals(outcome), "values": expected_values(outcome)}, "edge": edge, "target": target(s, rule), "criteria": criteria, "compare": {"literals": "word for word; case or spacing alone is formatting", "values": "exact by value for money, dates, status codes, IDs and counts; layout alone is formatting", "tolerance": "none"}}) for r in s["rules"]: - if r.get("class") == "design note": - continue # a technical step is built from its design note, not checked as behaviour + if r.get("class") in ("design note", "legacy interaction"): + continue # a technical step is built from its design note; the old screen's mechanics are not behaviour to keep for n, e in enumerate(r.get("examples") or [], 1): given = [(g["field"], g["value"]) for g in e.get("given") or []] edge = r.get("kind") in ("validation", "error_handling") or bool(EDGE_WORDS.search(e.get("then", ""))) @@ -130,6 +167,9 @@ def readme(datasets: list[dict[str, Any]]) -> str: "A quoted message must appear word for word, and money, dates, status codes, IDs and counts must have the same value. " "A difference only in how something is written (padding, case, spacing, an amount's or a date's layout) is reported as *formatting*, " "apart from a *business* difference. `compare.py` uses the Python standard library only; port it if your tests run elsewhere.", "", + "A case with nothing to compare (no quoted message and no stated value) is *unchecked*, and an unchecked case is never a pass: " + "`compare.py` exits 0 only when every case was checked and none differs, 1 when a case differs or was not answered, and 2 when " + "nothing differs but some cases were unchecked. Assert those outcomes in your own tests, then run it with `--allow-unchecked`.", "", f"## The datasets ({len(datasets)}, {total} cases)", "", "| Capability | Status | Cases | Edge cases | Uncovered |", "|---|---|---|---|---|"] lines += [f"| [{d['capability']}]({d['capability']}.json) {d['title']} | {d['status']} | {d['counts']['cases']} | {d['counts']['edge']} | " diff --git a/src/reframe/design/golden_compare.py b/src/reframe/design/golden_compare.py index bfeb8444..762c0186 100644 --- a/src/reframe/design/golden_compare.py +++ b/src/reframe/design/golden_compare.py @@ -9,6 +9,10 @@ {"OATM-C16-GD-01": {"text": "the message or output the system showed", "values": {"": ""}}} +Exit code: 0 when every case was checked and none differs; 1 when a case differs in business behaviour or was not +answered; 2 when nothing differs but some cases had nothing to compare (pass --allow-unchecked once your own tests assert +those outcomes). An unchecked case is never counted as equivalent. + Each expected value is compared by its kind. Money, dates, status codes, IDs and counts are compared exactly by value; a difference only in how the value is written (padding, case, an edited amount's layout, a date's layout) is reported as formatting, apart from a difference in business behaviour. A message the rule quotes must appear word for word: the @@ -115,11 +119,17 @@ def compare_case(case: dict[str, Any], actual: dict[str, Any] | None) -> dict[st return {"case": case["id"], "result": worst, "checks": checks} -def compare(dataset: dict[str, Any], actuals: dict[str, Any]) -> dict[str, Any]: +def compare(dataset: dict[str, Any], actuals: dict[str, Any], allow_unchecked: bool = False) -> dict[str, Any]: + """The comparison of every case. A case with nothing machine-checkable is "unchecked": it is never counted as + equivalent, because nothing was compared. `equivalent` needs every case checked and none different, unless + allow_unchecked says the unchecked ones are asserted by the team's own tests; `verified` says how many were checked.""" results = [compare_case(c, actuals.get(c["id"])) for c in dataset["cases"]] counts = {k: sum(1 for r in results if r["result"] == k) for k in (MATCH, FORMATTING, BUSINESS, MISSING, "unchecked")} + clean = counts[BUSINESS] == 0 and counts[MISSING] == 0 return {"dataset": dataset["dataset"], "capability": dataset["capability"], "expected_from": dataset["expected_from"], - "counts": counts, "equivalent": counts[BUSINESS] == 0 and counts[MISSING] == 0, "results": results} + "counts": counts, "verified": counts[MATCH] + counts[FORMATTING], "of": len(results), + "equivalent": clean and (counts["unchecked"] == 0 or allow_unchecked), "allow_unchecked": allow_unchecked, + "results": results} def main(argv: list[str] | None = None) -> int: @@ -127,12 +137,14 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("dataset") parser.add_argument("actual") parser.add_argument("--report", help="write the full report here as JSON") + parser.add_argument("--allow-unchecked", action="store_true", + help="accept cases with nothing to compare (their outcome is asserted by your own tests); without it they fail") args = parser.parse_args(argv) with open(args.dataset) as f: dataset = json.load(f) with open(args.actual) as f: actuals = json.load(f) - report = compare(dataset, actuals) + report = compare(dataset, actuals, args.allow_unchecked) if args.report: with open(args.report, "w") as f: json.dump(report, f, indent=1) @@ -142,9 +154,14 @@ def main(argv: list[str] | None = None) -> int: for r in report["results"]: if r["result"] in (BUSINESS, MISSING): print(f" {r['case']}: {r['result']}" + "".join(f"; {x['what']}: {x['result']}" for x in r["checks"] if x["result"] != MATCH)) + if c["unchecked"]: + print(f"{c['unchecked']} case(s) had nothing to compare, so they show nothing about equivalence: assert their outcome in your own " + "tests" + (", as --allow-unchecked says you do." if args.allow_unchecked else ", then run again with --allow-unchecked.")) if dataset["expected_from"] != "legacy outputs": print("The expected outputs come from the rules: equivalence is asserted from the rules, not proven against the legacy system.") - return 0 if report["equivalent"] else 1 + if c[BUSINESS] or c[MISSING]: + return 1 + return 0 if report["equivalent"] else 2 # 2: nothing differs, but some cases were not checked if __name__ == "__main__": diff --git a/src/reframe/design/package.py b/src/reframe/design/package.py index 7e9dedb2..cb5a6989 100644 --- a/src/reframe/design/package.py +++ b/src/reframe/design/package.py @@ -59,7 +59,9 @@ "ui-modernization": ("UI modernization", "Builds the modern screens to the prototype in ui-reference/ and the screen specifications.", ["Build to the prototype and the components listed; do not recreate 3270 habits (typed option codes, paging keys, one error at a time).", "Every validation shows the rule's own message; every input has a visible label; meet WCAG 2.2 AA.", - "Keep keyboard-heavy work fast: the shortcuts the screen specification gives, and a logical tab order."]), + "Keep keyboard-heavy work fast: the shortcuts the screen specification gives, and a logical tab order.", + "Rules classed legacy interaction (function keys, typed Y or N, cursor placement, paging keys, session plumbing) say what the " + "old screen did: build the modern equivalent the screen specification gives, never the key itself."]), "data": ("Data", "Models the data contracts on the target stack: tables, entities and their types.", ["Keep every field's precision: a packed decimal with 2 fraction digits is an exact decimal, never a float.", "Use synthetic data only; never copy production or personal data.", @@ -72,7 +74,9 @@ ["One test per acceptance criterion, named by its ID, asserting the Then exactly (messages word for word).", "Run the capability's golden dataset (golden/.json): each case's input through its target, the answers compared with " "golden/compare.py. A formatting difference is reported apart from a business one; a business difference fails.", - "A criterion that cannot be tested as written is reported, not changed."]), + "A criterion that cannot be tested as written is reported, not changed.", + "A criterion's legacy-interaction note names a key or typed answer the modern screen replaces: test the modern behaviour.", + "A golden case with nothing to compare is not a pass: assert its outcome in your own test, then run compare.py with --allow-unchecked."]), "compliance": ("Compliance", "Reviews capabilities that touch money, card data, personal data, security or audit.", ["Check card numbers, personal data and credentials are protected in storage, logs and screens.", "Check money is exact (decimal, never float) and every change to it is audited as the rules say.", @@ -160,11 +164,12 @@ def add(role: str, title: str, qs: list[dict[str, Any]], details: list[str], dep "requirements": [s["req_ids"][q["code"]] for q in qs], "rules": rules if rules is not None else rules_of(qs), "depends": depends, **extra}) - records = [b["copybook"] for b in s["contracts"] if b["role"] == "file record"] - working = [b["copybook"] for b in s["contracts"] if b["role"] != "file record"] + from reframe.design.specs import LEGACY, PERSISTENT + records = [b["copybook"] for b in s["contracts"] if b["role"] in PERSISTENT] + working = [b["copybook"] for b in s["contracts"] if b["role"] not in PERSISTENT] if s["contracts"]: add("data", "Model the data the capability reads and writes", reqs, - ([f"File records: {', '.join(records)} (see data-contracts.md)."] if records else []) + ([f"Stored records (file records, tables or entities): {', '.join(records)} (see data-contracts.md)."] if records else []) + ([f"Working records it passes or builds: {', '.join(working)}."] if working else []), [], rules=[], contracts=records + working) first = [found[0]["id"]] if found else [] core = by_class["business rule"] + by_class["side effect"] + by_class["historical artifact"] @@ -177,16 +182,27 @@ def add(role: str, title: str, qs: list[dict[str, Any]], details: list[str], dep 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", "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."], + # every capability gets its service or job task (P4-08, after review): the design notes' requirements when there are + # any, else every requirement it implements, so a job beside the screens is never left out + served = by_class["design note"] or [q for q in reqs if q["class"] != LEGACY] or reqs + add("api", f"Build {shape}", served, + notes or (["Expose the rules as the service the screens call."] if "online" in s["runs_as"] else []) + + ([f"Build the scheduled job: {', '.join(sorted({r['program'] for r in s['rules'] if r.get('program')}))} in the legacy source."] + if "scheduled job" in s["runs_as"] else []), [t["id"] for t in found if t["role"] in ("data", "business-rules")]) service = [t["id"] for t in found if t["role"] in ("api", "business-rules")] - for x in s["screens"]: - served = {k for c in x["components"] for k in c.get("requirements") or []} - qs = [q for q in reqs if q["key"] in served] or [q for q in reqs if set(q["rules"]) & {k for c in x["components"] for k in c.get("rules") or []}] + legacy = by_class[LEGACY] + for n, x in enumerate(s["screens"]): + cited = {k for c in x["components"] for k in c.get("requirements") or []} + qs = [q for q in reqs if q["key"] in cited] or [q for q in reqs if set(q["rules"]) & {k for c in x["components"] for k in c.get("rules") or []}] + if n == 0 and legacy: # the old screen's mechanics: the first screen task carries them, as what the modern screen replaces + qs = qs + [q for q in legacy if q not in qs] add("ui-modernization", f"Build the screen {x['title']} ({x['id']})", qs, [f"To the prototype: ui-reference/index.html#/{x['id']}."] + [f"{c.get('type', '')} \"{c.get('label', '')}\"" + (f": {c['validation']}" if c.get("validation") else "") for c in x["components"]], service, screen=x["id"]) + if legacy and not s["screens"]: + found[-1]["requirements"] += [s["req_ids"][q["code"]] for q in legacy if s["req_ids"][q["code"]] not in found[-1]["requirements"]] cases = (dataset or {}).get("cases") or [] add("test-generation", "Write a test for every acceptance criterion" + (", and run the golden dataset" if cases else ""), reqs, [f"{len(s['acceptance'])} acceptance criteria, each a test named by its ID."] @@ -211,7 +227,8 @@ def status_line(s: dict[str, Any]) -> str: def criterion(s: dict[str, Any], x: dict[str, Any]) -> str: rules = ", ".join(s["rule_ids"].get(k, k) for k in x["rules"]) - return f"GIVEN {md(x['given'])} WHEN {md(x['when'])} THEN {md(x['then'])} ({s['ac_ids'][x['id']]}{'; ' + rules if rules else ''})" + note = f" *{md(x['note'])}*" if x.get("note") else "" + return f"GIVEN {md(x['given'])} WHEN {md(x['when'])} THEN {md(x['then'])} ({s['ac_ids'][x['id']]}{'; ' + rules if rules else ''}){note}" def rules_table(s: dict[str, Any]) -> str: @@ -230,8 +247,10 @@ def examples(s: dict[str, Any]) -> str: def screens_md(s: dict[str, Any]) -> str: + context = [f"{md(x['title'])} ({x['id']})" for x in s.get("context_screens") or []] + also = f"Also in its journeys, with nothing of this capability: {', '.join(context)}." if context else "" if not s["screens"]: - return f"No screens: it runs as {s['runs_as']}." + return f"No screens: it runs as {s['runs_as']}." + (f" {also}" if also else "") out = [] for x in s["screens"]: out.append(f"### {md(x['title'])} ({x['id']})\n\n{md(x['purpose'])}\n\nPrototype: `ui-reference/index.html#/{x['id']}`." @@ -241,6 +260,12 @@ def screens_md(s: dict[str, Any]) -> str: reqs = ", ".join(s["req_ids"].get(k.rpartition("/")[2], "") for k in c.get("requirements") or [] if k.rpartition("/")[2] in s["req_ids"]) out.append(f"| {md(c.get('label', ''))} | {c.get('type', '')} | {md(c.get('shows', ''))} | {md(c.get('validation', ''))} | {c.get('goes_to', '')} | {reqs} |") out.append("") + if also: + out.append(also) + legacy = [r for r in s["rules"] if r.get("class") == "legacy interaction"] + if legacy: + out.append("\n**Legacy interaction to replace** (the old screen's mechanics; build the modern equivalent above, not the key):\n") + out += [f"- {s['rule_ids'].get(r['key'], r['key'])} {md(r.get('name', ''))}: {', '.join(r.get('mechanics') or [])}." for r in legacy] return "\n".join(out) @@ -250,10 +275,11 @@ def contracts_md(s: dict[str, Any], books: dict[str, Any]) -> str: c = books.get(b["copybook"]) if not c: continue - if b["role"] != "file record": + if b["role"] not in ("file record", "table", "entity"): out.append(f"- {b['copybook']} (working storage of {', '.join(b['programs'])}): see data-contracts.md.") continue - out.append(contract_md(c, f"File record of {', '.join(b['programs'])}.")) + what = {"file record": "File record", "table": "Table", "entity": "Entity"}[b["role"]] + out.append(contract_md(c, f"{what} of {', '.join(b['programs'])}.")) return "\n".join(out) or "None found in the source." @@ -718,7 +744,7 @@ def copy_out(folder, target: Path, form: str = "all") -> dict[str, Any]: source = folder.path(f"{FOLDER}/v{have[-1]}") if target.exists() and any(target.iterdir()): return {"written": 0, "left": [f"{target} is not empty: copy into an empty folder, so no filled-in file is overwritten"]} - cleaner = Cleaner(folder) + cleaner = Cleaner(folder, generic=False) # the application's own e-mail addresses and IDs stay (P4-08, after review) chosen = FORMS if form == "all" else (form,) planned, left = {}, [] for p in sorted(source.rglob("*")): diff --git a/src/reframe/design/specs.py b/src/reframe/design/specs.py index fe9ca402..db6207dc 100644 --- a/src/reframe/design/specs.py +++ b/src/reframe/design/specs.py @@ -51,7 +51,28 @@ # asks before carrying a historical artifact; technical steps become design notes. CLASS = {"business": "business rule", "validation": "business rule", "compliance": "business rule", "display": "formatting", "error_handling": "error handling", "side_effect": "side effect", "leftover": "historical artifact", "technical": "design note"} -CLASS_ORDER = ("business rule", "side effect", "error handling", "formatting", "historical artifact", "design note") +CLASS_ORDER = ("business rule", "side effect", "error handling", "formatting", "historical artifact", "legacy interaction", "design note") +LEGACY = "legacy interaction" +# The data contracts a capability keeps: a mainframe file record, an SQL table or an ORM entity (L1-06). The rest are +# records a program only builds or passes. +PERSISTENT = ("file record", "table", "entity") + +# The old screen's mechanics (P4-07, after review): a rule that is only about them says what the terminal did, not what +# the business needs, so it is classed "legacy interaction": the modern screen replaces it, and it gets no acceptance +# criterion. Read from the rule's words, with no model; a technical rule stays a design note. +KEY = r"(?:PF\s?\d{1,2}|PA\s?\d|F\d{1,2}|ENTER|CLEAR)" +MECHANICS_ONLY = ( + ("an unsupported key", re.compile(r"invalid key|any key other than|keys? other than|unsupported key|unrecogni[sz]ed key|no other key", re.I)), + ("cursor placement", re.compile(r"^\W*(?:(?:WHEN|IF) [^,]*,\s*(?:THEN\s+)?)?THE [^,]*? SHALL (?:place|put|position|move|set) the cursor", re.I)), + ("a paging key", re.compile(r"\b(?:PF\s?[78]|F[78])\b|\bpag(?:e|es|ing) (?:forward|backward|back|up|down)\b", re.I)), + ("an exit key", re.compile(rf"\b(?:on|with|presses|pressed)\s+{KEY}\b[^.]*\b(?:return|exit|leave|back to|transfer|go(?:es)? to)\b" + rf"|\b(?:return|exit|leave)\w*\b[^.]*\b(?:on|with)\s+{KEY}\b", re.I)), + ("session plumbing", re.compile(r"EIBCALEN|COMMAREA|pseudo-?conversational|RETURN TRANSID|first time (?:in|into|through)|re-?entry|" + r"on re-?entering|\bsender\b|calling program|\bcaller\b", re.I)), +) +# Mentions of the old screen's mechanics in a rule that keeps its business meaning: its criteria carry a note, so the +# team builds the modern equivalent the screen specification gives, not the key or the typed answer. +MENTIONS = re.compile(rf"\b{KEY}\b|\((?:Y/N|Y or N)\)|\bY or N\b|\btyp(?:e|es|ing) [YN]\b|\bcursor\b|EIBCALEN|EIBAID|COMMAREA", re.I) SCHEMA = {"type": "object", "required": ["capabilities"], "properties": { "capabilities": {"type": "array", "items": {"type": "object", "required": ["key", "summary", "acceptance", "design_notes"], "properties": { @@ -97,9 +118,23 @@ def class_of(kind: str) -> str: return CLASS.get(kind or "", "business rule") +def mechanics_of(rule: dict[str, Any]) -> list[str]: + """Which of the old screen's mechanics a rule is only about (empty when it is about the business).""" + text = f"{rule.get('name', '')} {rule.get('text', '')}" + return [what for what, rx in MECHANICS_ONLY if rx.search(text)] + + +def class_for(rule: dict[str, Any]) -> str: + """A rule's class: from its kind, except that a rule only about the old screen's mechanics is legacy interaction.""" + kind = rule.get("kind", "") + if kind != "technical" and mechanics_of(rule): + return LEGACY + return class_of(kind) + + def requirement_class(rules: list[dict[str, Any]]) -> str: """A requirement's class: the first of its rules' classes in CLASS_ORDER.""" - found = {class_of(r.get("kind", "")) for r in rules} + found = {class_for(r) for r in rules} return next((c for c in CLASS_ORDER if c in found), "business rule") @@ -108,16 +143,27 @@ def requirement_class(rules: list[dict[str, Any]]) -> str: def when_of(rule: dict[str, Any]) -> str: - """The trigger of a rule in EARS form ("WHEN x, THE y SHALL z" gives "x"), or " runs".""" + """The trigger of a rule in EARS form ("WHEN x, THE y SHALL z" gives "x"), or " runs". A trigger written as two + ("WHEN x, WHEN y") is joined into one ("x and y").""" text = rule.get("text", "") m = TRIGGER.match(text) if m: - return re.sub(r"\s+", " ", m.group(1)).strip() + trigger = re.sub(r"\s+", " ", m.group(1)).strip() + return re.sub(r",?\s+(?:WHEN|IF)\s+", " and ", trigger) m = SUBJECT.match(text) subject = re.sub(r"\s+", " ", m.group(1)).strip() if m else "" return f"{subject} runs" if m else f"{rule.get('name') or 'the rule'} applies" +def event_of(rule: dict[str, Any]) -> str: + """What happens in a worked example, without the rule's condition: " processes these inputs". + The condition belongs to the rule; a worked example may show the case it is not met (P4-07, after review), so the + example's criterion never restates it.""" + m = re.search(r"(?:^\s*|,\s*(?:THEN\s+)?)THE\s+(.+?)\s+SHALL\b", rule.get("text", ""), re.I | re.S) + subject = re.sub(r"\s+", " ", m.group(1)).strip() if m else "" + return f"the {subject} processes these inputs" if subject else f"{rule.get('name') or 'the system'} is applied to these inputs" + + def given_of(example: dict[str, Any]) -> str: given = [f"{g.get('field', '')}: {g.get('value', '')}" for g in example.get("given") or []] return "; ".join(given) if given else "no particular input" @@ -133,9 +179,16 @@ def example_criteria(reqs: list[dict[str, Any]], rules: dict[str, Any]) -> list[ found = [] for k, codes in behind.items(): r = rules.get(k) or {} + if class_for(r) == LEGACY: + continue # the old screen's mechanics: the modern screen replaces them, so no criterion + mentions = list(dict.fromkeys(m.group(0) for m in MENTIONS.finditer(r.get("text", "")))) for i, x in enumerate(r.get("examples") or [], 1): - found.append({"requirements": codes, "rules": [k], "given": given_of(x), "when": when_of(r), "then": str(x.get("then", "")), - "from": f"worked example {i} of the rule"}) + item = {"requirements": codes, "rules": [k], "given": given_of(x), "when": event_of(r), "then": str(x.get("then", "")), + "from": f"worked example {i} of the rule"} + if mentions: + item["note"] = ("Legacy interaction: " + ", ".join(mentions) + ". The modern screen replaces it; build and test the " + "equivalent its screen specification gives, not the key or the typed answer.") + found.append(item) return found @@ -185,10 +238,8 @@ def screens_for(key: str, codes: set[str], rule_keys: set[str], modern: dict[str found = [] for s in modern.get("screens") or []: parts = [c for c in s.get("components") or [] if set(c.get("requirements") or []) & codes or set(c.get("rules") or []) & rule_keys] - if not parts and not set(s.get("journeys") or []) & set(mine): - continue - if not parts and not s.get("replaces"): - continue # the shared header and navigation, in every journey + if not parts: + continue # a screen of the journey with nothing of this capability: named as context (context_screens), not specified how: dict[str, int] = defaultdict(int) for m in s.get("replaces") or []: for h, n in mapping.get(m, {}).items(): @@ -201,6 +252,15 @@ def screens_for(key: str, codes: set[str], rule_keys: set[str], modern: dict[str return found, mine +def context_screens(key: str, found: list[dict[str, Any]], modern: dict[str, Any], journeys: list[dict[str, Any]]) -> list[dict[str, str]]: + """The other screens of the capability's journeys: named, with no component table, since none of their components + serves it (P4-07, after review).""" + mine = {j["id"] for j in journeys if key in (j.get("capabilities") or [])} + have = {x["id"] for x in found} + return [{"id": s["id"], "title": s.get("title", "")} for s in modern.get("screens") or [] + if s["id"] not in have and set(s.get("journeys") or []) & mine and s.get("replaces")] + + def questions_for(rule_keys: list[str], rules: dict[str, Any], sme: list[dict[str, Any]], own: list[Any]) -> list[dict[str, Any]]: """The SME list's open questions on the capability's rules (matched through the input rules each recommended rule covers), and the capability's own questions from the requirements.""" @@ -254,13 +314,18 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None mine = [rules[k] for k in rule_keys if k in rules] codes = {f"{page}/{q['code']}" for q in reqs} screens, journey_ids = screens_for(key, codes, set(rule_keys), modern, journeys) + context = context_screens(key, screens, modern, journeys) + shown = {x["id"] for x in screens} | {x["id"] for x in context} + # every screen of the capability's journeys, in order, as the model step reads them: unchanged by the review's + # split into specified and context screens, so a saved answer still fits + titles = [x.get("title", "") for x in modern.get("screens") or [] if x["id"] in shown] programs = sorted({str(r.get("program", "")).upper() for r in mine if r.get("program")}) books: dict[str, dict[str, Any]] = {} for p in programs: for b, role in (uses.get(p) or {}).items(): entry = books.setdefault(b, {"copybook": b, "role": role, "programs": []}) entry["programs"].append(p) - if role == "file record": + if role in PERSISTENT: entry["role"] = role criteria = example_criteria(reqs, rules) covered = {c for x in criteria for c in x["requirements"]} @@ -272,14 +337,16 @@ def assemble(folder, legacy: Path | None, signoffs: list[dict[str, Any]] | None "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", "")), + "rules": [{"key": r["key"], "name": r.get("name", ""), "kind": r.get("kind", ""), "class": class_for(r), + **({"mechanics": mechanics_of(r)} if class_for(r) == LEGACY else {}), "confidence": r.get("confidence", ""), "decision": r.get("decision", ""), "program": r.get("program", ""), "text": r["text"], "examples": r.get("examples") or [], "evidence": r.get("evidence") or []} for r in mine], "acceptance": criteria, - "needs_criteria": [q["code"] for q in reqs if q["code"] not in covered], + "needs_criteria": [q["code"] for q in reqs if q["code"] not in covered + and requirement_class([rules[k] for k in q.get("rules") or [] if k in rules]) != LEGACY], "technical_rules": [r["key"] for r in mine if r.get("kind") == "technical"], - "screens": screens, "journeys": journey_ids, - "contracts": sorted(books.values(), key=lambda b: (b["role"] != "file record", b["copybook"])), + "screens": screens, "journeys": journey_ids, "context_screens": context, "screen_titles": titles, + "contracts": sorted(books.values(), key=lambda b: (b["role"] not in PERSISTENT, b["copybook"])), "tables": cap.get("tables") or [], "questions": questions_for(rule_keys, rules, sme, cap.get("questions") or []), }) @@ -306,7 +373,7 @@ def batch_input(mine: list[dict[str, Any]]) -> dict[str, Any]: "key": s["key"], "title": s["title"], "story": s["story"], "runs_as": s["runs_as"], "requirements": [{"code": q["code"], "text": q["text"], "rules": q["rules"]} for q in s["requirements"]], "rules": [{"key": r["key"], "kind": r["kind"], "name": r["name"], "text": r["text"][:400]} for r in s["rules"]], - "screens": [x["title"] for x in s["screens"]], + "screens": s.get("screen_titles", [x["title"] for x in s["screens"]]), "needs_criteria": s["needs_criteria"], "technical_rules": s["technical_rules"]} for s in mine]} @@ -375,7 +442,7 @@ def problems(answer: dict[str, Any] | None, data: dict[str, Any]) -> list[str]: def finish(spec: dict[str, Any], written: dict[str, Any] | None) -> dict[str, Any]: """A specification with the model's parts added, and its acceptance criteria numbered.""" written = written or {} - out = {k: v for k, v in spec.items() if k not in ("needs_criteria", "technical_rules")} + out = {k: v for k, v in spec.items() if k not in ("needs_criteria", "technical_rules", "screen_titles")} out["summary"] = written.get("summary", "") criteria = list(spec["acceptance"]) + [{"requirements": [x["requirement"]], "rules": x.get("rules") or [], "given": x["given"], "when": x["when"], "then": x["then"], "from": "written from the rule"} for x in written.get("acceptance") or [] diff --git a/src/reframe/report/backlog.py b/src/reframe/report/backlog.py index 44b33f7d..061ad3e9 100644 --- a/src/reframe/report/backlog.py +++ b/src/reframe/report/backlog.py @@ -58,7 +58,8 @@ def _label(text: str) -> str: def _criteria(s: dict[str, Any]) -> list[str]: rid = s["rule_ids"] return [f"{s['ac_ids'][x['id']]}: Given {x['given']} When {x['when']} Then {x['then']}" - + (f" ({', '.join(rid.get(k, k) for k in x.get('rules') or [])})" if x.get("rules") else "") for x in s["acceptance"]] + + (f" ({', '.join(rid.get(k, k) for k in x.get('rules') or [])})" if x.get("rules") else "") + + (f" Note: {x['note']}" if x.get("note") else "") for x in s["acceptance"]] def _parts(s: dict[str, Any]) -> dict[str, list[str]]: diff --git a/src/reframe/report/publish.py b/src/reframe/report/publish.py index 5055d74c..e15f8624 100644 --- a/src/reframe/report/publish.py +++ b/src/reframe/report/publish.py @@ -32,9 +32,15 @@ class Cleaner: - """The run's own identifiers, and the generic kinds, replaced by placeholders.""" + """The run's own identifiers, and the generic kinds, replaced by placeholders. - def __init__(self, folder: RunFolder) -> None: + `generic` (the default, for anything published) also replaces every e-mail address and ID. A package copied out for + the team that builds from it (P4-08, after review) passes generic=False: it keeps the e-mail addresses and IDs that + are the application's own data, such as a validation rule's sample address or a golden case's input, and is still + cleaned of the account, ARNs, S3 locations, the AWS profile, the run's resources, local paths and API keys.""" + + def __init__(self, folder: RunFolder, generic: bool = True) -> None: + self.generic = generic state = folder.state self.exact: list[tuple[str, str]] = [] account = str(state.get("account") or "") @@ -65,9 +71,10 @@ def clean(self, text: str) -> str: text = S3_URI.sub("s3://", text) if self.resources is not None: text = self.resources.sub("", text) - # each distinct ID gets a stable stand-in, so keys and links that use it stay unique - text = UUID.sub(lambda m: "id-" + hashlib.sha256(m.group(0).lower().replace("_", "-").encode()).hexdigest()[:10], text) - text = EMAIL.sub("", text) + if self.generic: + # each distinct ID gets a stable stand-in, so keys and links that use it stay unique + text = UUID.sub(lambda m: "id-" + hashlib.sha256(m.group(0).lower().replace("_", "-").encode()).hexdigest()[:10], text) + text = EMAIL.sub("", text) text = API_KEY.sub("", text) if self.profile is not None: text = self.profile.sub("", text) @@ -75,8 +82,10 @@ def clean(self, text: str) -> str: def left(self, text: str) -> list[str]: found = [] - for name, pattern in (("an ARN", ARN), ("an S3 location", re.compile(r"s3://(?!)[a-z0-9]", re.I)), ("an ID", UUID), ("an e-mail address", EMAIL), - ("an API key", API_KEY)): + kinds = [("an ARN", ARN), ("an S3 location", re.compile(r"s3://(?!)[a-z0-9]", re.I)), ("an API key", API_KEY)] + if self.generic: + kinds += [("an ID", UUID), ("an e-mail address", EMAIL)] + for name, pattern in kinds: if pattern.search(text): found.append(name) for old, _ in self.exact: diff --git a/tests/design/test_golden.py b/tests/design/test_golden.py index 6633add3..5c8fc018 100644 --- a/tests/design/test_golden.py +++ b/tests/design/test_golden.py @@ -111,9 +111,11 @@ def test_a_dataset_is_equivalent_when_no_case_differs_in_business_or_is_unanswer "OATM-C16-GD-02": {"text": "Saved"}, "OATM-C16-GD-04": {"text": "Cancelled"}} report = golden_compare.compare(d, actual) self.assertEqual(report["counts"], {"match": 1, "formatting": 1, "business": 0, "missing": 0, "unchecked": 2}) - self.assertTrue(report["equivalent"]) + self.assertFalse(report["equivalent"]) # two cases had nothing to compare: never a pass (#421, after review) + self.assertEqual((report["verified"], report["of"]), (2, 4)) + self.assertTrue(golden_compare.compare(d, actual, allow_unchecked=True)["equivalent"]) # the team asserts those two itself del actual["OATM-C16-GD-03"] - self.assertFalse(golden_compare.compare(d, actual)["equivalent"]) + self.assertFalse(golden_compare.compare(d, actual, allow_unchecked=True)["equivalent"]) def test_values_to_compare_are_compared_by_kind(self): case = {"id": "X-GD-01", "expected": {"outcome": "", "literals": [], "values": [{"field": "balance", "value": "100.00", "kind": "money"}]}} diff --git a/tests/design/test_package.py b/tests/design/test_package.py index 6ca6be79..7a1059f5 100644 --- a/tests/design/test_package.py +++ b/tests/design/test_package.py @@ -33,7 +33,7 @@ def test_three_forms_with_every_id_traced(self): self.assertEqual(len(list((root / "spec-kit/.claude/agents").glob("*.md"))), 6) kiro = (root / "kiro/.kiro/specs/sig-01-sign-on/requirements.md").read_text() self.assertIn("**Status: FINAL**, signed off by Pat, 2026-11-25.", kiro) - self.assertIn("GIVEN USERID: ADMIN001; PASSWD: WRONG WHEN the password does not match THEN it shows 'Wrong Password. Try again ...' (SIG-C01-AC-01; SIG-BR-001)", kiro) + self.assertIn("GIVEN USERID: ADMIN001; PASSWD: WRONG WHEN the sign-on processes these inputs THEN it shows 'Wrong Password. Try again ...' (SIG-C01-AC-01; SIG-BR-001)", kiro) self.assertIn("**Status: DRAFT**", (root / "kiro/.kiro/specs/va-01-view-an-account/design.md").read_text()) design = (root / "kiro/.kiro/specs/va-01-view-an-account/design.md").read_text() self.assertIn("Record `ACCOUNT-RECORD`", design) diff --git a/tests/design/test_review_fixes.py b/tests/design/test_review_fixes.py new file mode 100644 index 00000000..a45db26e --- /dev/null +++ b/tests/design/test_review_fixes.py @@ -0,0 +1,179 @@ +"""The forward-engineering review of 28 November 2026: P4-07 (#393), P4-08 (#394), P4-11 (#421) and L1-06 (#478).""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from reframe.design import golden, golden_compare, package, specs +from reframe.report.publish import Cleaner + +KEYS = "rec/x/RULE-1" + + +def rule(text, kind="validation", name="", examples=None, key=KEYS): + return {"key": key, "text": text, "kind": kind, "name": name, "examples": examples or [], "program": "COACTUPC", "evidence": []} + + +class AcceptanceCriteriaTest(unittest.TestCase): + """P4-07: an example's criterion never restates a condition it may not meet; a double WHEN reads as one.""" + + def test_an_example_gets_the_event_not_the_rules_condition(self): + r = rule("WHEN a user whose type is anything other than 'A' signs on, THE sign-on SHALL send the user to the main menu", + examples=[{"given": [{"field": "User Type", "value": "A"}], "then": "the admin menu"}]) + [c] = specs.example_criteria([{"code": "REQ-F-001", "rules": [KEYS]}], {KEYS: r}) + self.assertEqual((c["given"], c["when"]), ("User Type: A", "the sign-on processes these inputs")) + self.assertNotIn("other than", c["when"]) + + def test_a_double_when_is_joined(self): + r = rule("WHEN no error has been flagged, WHEN the account balance is zero or less, THE bill payment SHALL refuse it") + self.assertEqual(specs.when_of(r), "no error has been flagged and the account balance is zero or less") + + +class LegacyInteractionTest(unittest.TestCase): + """P4-07: the old screen's mechanics are legacy interaction, with no acceptance criterion; a business rule that only + mentions a key keeps its criteria, with a note.""" + + def test_rules_only_about_the_terminal_are_legacy_interaction(self): + for text in ("WHEN the user presses any key other than Enter, PF3 or PF5, THE Transaction View SHALL show 'Invalid key pressed'", + "THE card detail screen SHALL place the cursor on the account field when it is invalid", + "WHEN the user presses PF8 and no further page exists, THE list SHALL keep the current page", + "WHEN the user presses PF3 on the list, THE list SHALL return to the main menu", + "WHEN the program is started without any session data (no commarea), THE list SHALL transfer to sign-on"): + self.assertEqual(specs.class_for(rule(text)), specs.LEGACY, text) + self.assertEqual(specs.class_for(rule("WHEN the Tran ID filter is not numeric, THE list SHALL show 'Tran ID must be Numeric'")), "business rule") + self.assertEqual(specs.class_for(rule("WHEN control leaves on PF3, THE program SHALL pass the commarea", kind="technical")), "design note") + + def test_legacy_interaction_gets_no_criterion_and_a_mention_gets_a_note(self): + mech = rule("WHEN the user presses any key other than Enter, THE screen SHALL show 'Invalid key pressed'", key="k1", + examples=[{"given": [{"field": "key", "value": "PF5"}], "then": "'Invalid key pressed'"}]) + save = rule("WHEN validated changes are confirmed with PF5, THE account update SHALL save them", kind="business", key="k2", + examples=[{"given": [{"field": "changes", "value": "valid"}], "then": "saved"}]) + found = specs.example_criteria([{"code": "REQ-F-001", "rules": ["k1", "k2"]}], {"k1": mech, "k2": save}) + self.assertEqual([c["rules"] for c in found], [["k2"]]) + self.assertIn("Legacy interaction: PF5", found[0]["note"]) + self.assertEqual(specs.requirement_class([mech]), specs.LEGACY) + self.assertEqual(specs.requirement_class([mech, save]), "business rule") + + +class ScreensTest(unittest.TestCase): + """P4-07: a journey screen with nothing of the capability is named as context, with no empty component table.""" + + def test_only_screens_with_components_are_specified(self): + modern = {"screens": [{"id": "S-BILL-PAY", "journeys": ["J1"], "replaces": ["COBIL0A"], "components": [{"id": "pay", "rules": [KEYS]}]}, + {"id": "S-ACCOUNT-VIEW", "title": "Account", "journeys": ["J1"], "replaces": ["CACTVWA"], "components": [{"id": "x", "rules": ["other"]}]}]} + journeys = [{"id": "J1", "capabilities": ["cap"]}] + found, mine = specs.screens_for("cap", set(), {KEYS}, modern, journeys) + self.assertEqual(([x["id"] for x in found], mine), (["S-BILL-PAY"], ["J1"])) + self.assertEqual(specs.context_screens("cap", found, modern, journeys), [{"id": "S-ACCOUNT-VIEW", "title": "Account"}]) + md = package.screens_md({"screens": [], "context_screens": [{"id": "S-ACCOUNT-VIEW", "title": "Account"}], "runs_as": "online", "rules": []}) + self.assertIn("Also in its journeys, with nothing of this capability: Account (S-ACCOUNT-VIEW).", md) + self.assertNotIn("| Component |", md) + + +def labelled(**over): + s = {"id": "OATM-C19", "runs_as": "online and scheduled job", "screens": [{"id": "S-BILL-PAY", "title": "Pay", "purpose": "Pay a bill", "replaces": ["COBIL0A"], "components": [{"type": "button", "label": "Pay", "rules": [KEYS], "requirements": ["rec/x/REQ-F-001"]}]}], + "requirements": [{"code": "REQ-F-001", "key": "rec/x/REQ-F-001", "class": "business rule", "rules": [KEYS]}, + {"code": "REQ-F-002", "key": "rec/x/REQ-F-002", "class": "legacy interaction", "rules": ["k2"]}], + "rules": [{"key": KEYS, "program": "COBIL00C", "class": "business rule"}, {"key": "k2", "program": "COBIL00C", "class": "legacy interaction", + "name": "Reject unsupported key", "mechanics": ["an unsupported key"]}], + "design_notes": [], "contracts": [{"copybook": "ACCOUNTS", "role": "table", "programs": ["COBIL00C"]}], + "acceptance": [], "touches": [], "req_ids": {"REQ-F-001": "OATM-REQ-F-001", "REQ-F-002": "OATM-REQ-F-002"}, + "rule_ids": {KEYS: "OATM-BR-001", "k2": "OATM-BR-002"}, "ac_ids": {}} + s.update(over) + return s + + +class PackageTasksTest(unittest.TestCase): + """P4-08: every capability gets its service or job task; tables and entities are stored records; legacy interaction + goes to the screen task.""" + + def test_a_job_beside_the_screens_gets_its_task(self): + ts = package.tasks(labelled()) + api = next(t for t in ts if t["role"] == "api") + self.assertEqual(api["title"], "Build the services and the scheduled job") + self.assertIn("OATM-REQ-F-001", api["requirements"]) + self.assertTrue(any("scheduled job: COBIL00C" in d for d in api["details"])) + + def test_tables_and_entities_are_stored_records(self): + data = next(t for t in package.tasks(labelled()) if t["role"] == "data") + self.assertIn("Stored records (file records, tables or entities): ACCOUNTS", data["details"][0]) + book = {"copybook": "ACCOUNTS", "file": "db/schema.sql", "records": [{"name": "accounts", "fields": [ + {"name": "id", "group": "", "pic": "integer", "usage": "", "says": "a whole number", "stack": {}}]}]} + md = package.contracts_md(labelled(), {"ACCOUNTS": book}) + self.assertIn("Table of COBIL00C.", md) + self.assertIn("| id |", md) + self.assertNotIn("working storage", md) + + def test_legacy_interaction_goes_to_the_screen_task(self): + ui = next(t for t in package.tasks(labelled()) if t["role"] == "ui-modernization") + self.assertIn("OATM-REQ-F-002", ui["requirements"]) + md = package.screens_md(labelled()) + self.assertIn("**Legacy interaction to replace**", md) + self.assertIn("OATM-BR-002 Reject unsupported key: an unsupported key.", md) + + +class CleanerScopeTest(unittest.TestCase): + """P4-08: a package copied out for the team keeps the application's own e-mail addresses and IDs.""" + + def test_the_package_scope_keeps_application_data_and_still_strips_the_account(self): + from reframe.core.runfolder import new_run + with tempfile.TemporaryDirectory() as tmp, mock.patch.dict(os.environ, {"REFRAME_HOME": tmp}): + folder = new_run("demo") + folder.update(project="demo", account="123456789012", profile="team-dev") + text = "sample user@example.com, id 1f5b9b93-67ea-4ee8-9804-248082449101, account 123456789012, profile team-dev" + narrow = Cleaner(folder, generic=False).clean(text) + self.assertIn("user@example.com", narrow) + self.assertIn("1f5b9b93-67ea-4ee8-9804-248082449101", narrow) + self.assertNotIn("123456789012", narrow) + self.assertNotIn("team-dev", narrow) + self.assertEqual(Cleaner(folder, generic=False).left(narrow), []) + self.assertIn("", Cleaner(folder).clean(text)) # anything published is still cleaned of both + + +class GoldenValuesTest(unittest.TestCase): + """P4-11: expected values read from the outcome; legacy interaction has no cases; unchecked is never equivalent.""" + + def test_values_an_outcome_states(self): + self.assertEqual(golden.expected_values("The output record's cycle debit (OUT-ACCT-CURR-CYC-DEBIT) is 2525.00."), + [{"field": "OUT-ACCT-CURR-CYC-DEBIT", "value": "2525.00", "kind": "money"}]) + self.assertEqual(golden.expected_values("the declined count is 2 and the declined total is 110.00"), + [{"field": "declined count", "value": "2", "kind": "count"}, {"field": "declined total", "value": "110.00", "kind": "money"}]) + self.assertEqual(golden.expected_values("Record B is printed before record A"), []) + + def test_a_case_compares_its_values_and_legacy_interaction_has_none(self): + spec = {"id": "X-C01", "title": "x", "status": "draft", "runs_as": "scheduled job", "screens": [], "acceptance": [], "ac_ids": {}, "tables": [], + "rule_ids": {"a": "X-BR-001", "b": "X-BR-002"}, + "rules": [{"key": "a", "class": "business rule", "kind": "business", "program": "P", "evidence": [], + "examples": [{"given": [], "then": "the account total resets to 0"}]}, + {"key": "b", "class": "legacy interaction", "kind": "validation", "program": "P", "evidence": [], + "examples": [{"given": [], "then": "'Invalid key pressed'"}]}]} + d = golden.dataset(spec) + self.assertEqual([c["rule"] for c in d["cases"]], ["X-BR-001"]) + self.assertEqual(d["cases"][0]["expected"]["values"], [{"field": "account total", "value": "0", "kind": "count"}]) + report = golden_compare.compare(d, {"X-C01-GD-01": {"values": {"account total": "00"}}}) + self.assertEqual((report["counts"]["formatting"], report["equivalent"]), (1, True)) + report = golden_compare.compare(d, {"X-C01-GD-01": {"values": {"account total": "5"}}}) + self.assertEqual((report["counts"]["business"], report["equivalent"]), (1, False)) + + def test_the_command_fails_while_cases_are_unchecked(self): + d = {"dataset": "X-GD", "capability": "X", "expected_from": "the rules", + "cases": [{"id": "X-GD-01", "expected": {"outcome": "the list is shown", "literals": [], "values": []}}]} + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "d.json").write_text(json.dumps(d)) + (tmp / "a.json").write_text(json.dumps({"X-GD-01": {"text": "shown"}})) + script = Path(golden_compare.__file__) + run = lambda *extra: subprocess.run([sys.executable, "-I", str(script), str(tmp / "d.json"), str(tmp / "a.json"), *extra], # noqa: E731 + capture_output=True, text=True) + first = run() + self.assertEqual(first.returncode, 2) + self.assertIn("1 case(s) had nothing to compare", first.stdout) + self.assertEqual(run("--allow-unchecked").returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/design/test_specs.py b/tests/design/test_specs.py index 9889e2e3..7a9ce23b 100644 --- a/tests/design/test_specs.py +++ b/tests/design/test_specs.py @@ -108,7 +108,7 @@ def test_specifications_assembled_checked_and_kept(self): # acceptance criteria: one per worked example, then the written ones; every requirement has one first = acct["acceptance"][0] self.assertEqual((first["id"], first["given"], first["when"], first["then"]), - ("AC-01", "ACCT-ID: (blank)", "the account number is blank", "it shows 'Enter an account'")) + ("AC-01", "ACCT-ID: (blank)", "the account view processes these inputs", "it shows 'Enter an account'")) self.assertEqual(acct["acceptance"][1]["given"], "no particular input") self.assertEqual([x["from"] for x in sign["acceptance"]], ["worked example 1 of the rule", "written from the rule"]) self.assertEqual({q["code"]: q["criteria"] for q in sign["requirements"]}, {"REQ-F-001": ["AC-01"], "REQ-F-002": ["AC-02"]}) diff --git a/tests/report/test_backlog.py b/tests/report/test_backlog.py index 4e91ce7e..f82e082b 100644 --- a/tests/report/test_backlog.py +++ b/tests/report/test_backlog.py @@ -36,7 +36,7 @@ def test_jira_has_an_epic_per_function_and_a_story_per_capability_with_the_packa sign_on = next(s for s in stories if s[2].startswith("SIG-C01")) self.assertIn("SIG-REQ-F-", sign_on[4]) self.assertIn("h3. Acceptance criteria", sign_on[4]) - self.assertIn("SIG-C01-AC-01: Given USERID: ADMIN001; PASSWD: WRONG When the password does not match Then it shows 'Wrong Password. Try again ...' (SIG-BR-001)", + self.assertIn("SIG-C01-AC-01: Given USERID: ADMIN001; PASSWD: WRONG When the sign-on processes these inputs Then it shows 'Wrong Password. Try again ...' (SIG-BR-001)", sign_on[5]) self.assertIn("Golden dataset: golden/SIG-C01.json", sign_on[4]) self.assertEqual(sign_on[8:12][2], "final")