diff options
Diffstat (limited to 'plugins/code-modernization')
4 files changed, 79 insertions, 27 deletions
diff --git a/plugins/code-modernization/commands/modernize-assess.md b/plugins/code-modernization/commands/modernize-assess.md index a9b6b752..e02f5625 100644 --- a/plugins/code-modernization/commands/modernize-assess.md +++ b/plugins/code-modernization/commands/modernize-assess.md @@ -139,8 +139,13 @@ Inventory** · **Architecture at a Glance** (domain table, refer to the diagram) plainly that it is not a timeline or a cost, and print no person-months, schedule, cost or date) · **Recommended Modernization Pattern**: one of Rehost, Replatform, Refactor, Rearchitect, Rebuild, Replace, with a one-paragraph rationale and the -command it routes to (same-stack version bump → `uplift`; cross-stack rearchitect -→ `transform`; rebuild → `reimagine`). +command it routes to: a move to a newer version of the same technology (or its +supporting platform) → `uplift`; a rewrite in another technology, piece by piece → +`transform`; a rebuild on a new architecture → `reimagine`. Rehost (move as is) and +Replace (buy or adopt a product) change no code, so no build command applies: say so, +and say what the analysis is still good for. For Rehost, `map`, `harden` and the `preflight` +build check show what the move must carry along; for Replace, `extract-rules` turns +what the system does into the acceptance criteria a replacement is judged against. Also write `analysis/$system/ARCHITECTURE.mmd`, the domain diagram from the legacy-analyst. diff --git a/plugins/code-modernization/scripts/compare.py b/plugins/code-modernization/scripts/compare.py index ca3c2469..137007f1 100644 --- a/plugins/code-modernization/scripts/compare.py +++ b/plugins/code-modernization/scripts/compare.py @@ -29,9 +29,10 @@ compiler or math library) can be compared within a declared tolerance, per case "tolerance": {"rel": 1e-9, "abs": 0, "why": "last-digit rounding of the exp() in the interest formula"} The reason is required and is recorded. Only numbers written with a decimal point or an exponent -may differ, and only within the tolerance; every other byte, and every integer, must match exactly. -The case is `same`, with the largest relative difference recorded; anything outside the tolerance -is `differs`. A relative tolerance above 1% is refused: that is a different result, not rounding. +may differ, and only within the tolerance (compared as exact decimals); every other byte, every integer and every +dotted run like 1.2.3 must match exactly. The case is `same`, with the largest relative difference +recorded; anything outside the tolerance is `differs`. A relative tolerance above 1% or an absolute one +above 1e-6 is refused: that is a different result, not rounding. Writes EQUIVALENCE.json (default: next to the cases file). Exit 0 only when at least one case executed, none is missing or differs (approved differences are allowed), the self-check did not @@ -41,6 +42,7 @@ import argparse import bisect import datetime import hashlib +import decimal import json import math import os @@ -51,7 +53,10 @@ import tempfile MARK = b"\x00<MASK>\x00" MAX_BYTES = 256 * 1024 * 1024 MAX_TOLERANT_BYTES = 32 * 1024 * 1024 -NUMBER = re.compile(rb"[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?") +# A dotted run such as 1.2.3 or 10.0.0.1 is an identifier, not a number: it is left inside the text around it. +NUMBER = re.compile(rb"(?P<dotted>\d+(?:\.\d+){2,})|(?P<num>[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?)") +MAX_ABS_TOLERANCE = 1e-6 +MAX_NUMBER_CHARS = 64 class InputError(Exception): @@ -99,6 +104,8 @@ def parse_tolerance(spec, cid): raise InputError("case %s: give a positive rel or abs tolerance" % cid) if rel > 0.01: raise InputError("case %s: a relative tolerance above 1%% is a different result, not rounding" % cid) + if ab > MAX_ABS_TOLERANCE: + raise InputError("case %s: an absolute tolerance above %g is a different result, not rounding" % (cid, MAX_ABS_TOLERANCE)) why = clip(spec.get("why"), 300).strip() if not why: raise InputError("case %s: a tolerance needs a 'why' saying what legitimately differs" % cid) @@ -109,6 +116,8 @@ def split_numbers(data): """-> [(is_number, bytes, offset)] covering `data` end to end.""" parts, pos = [], 0 for m in NUMBER.finditer(data): + if m.group("dotted") is not None: + continue if m.start() > pos: parts.append((False, data[pos:m.start()], pos)) parts.append((True, m.group(), m.start())) @@ -129,6 +138,7 @@ def within_tolerance(a, b, tol): ta, tb = split_numbers(a), split_numbers(b) if len(ta) != len(tb): return False, first_diff(a, b) or 0 + allow_abs, allow_rel = decimal.Decimal(repr(tol["abs"])), decimal.Decimal(repr(tol["rel"])) differing, worst = 0, 0.0 for (na, xa, sa), (nb, xb, _) in zip(ta, tb): if xa == xb: @@ -137,19 +147,20 @@ def within_tolerance(a, b, tol): return False, sa if not na: return False, sa + (first_diff(xa, xb) or 0) - if not (is_float(xa) and is_float(xb)): - return False, sa # an integer must match exactly - try: - x, y = float(xa), float(xb) - except ValueError: - return False, sa - if not (math.isfinite(x) and math.isfinite(y)): - return False, sa - scale = max(abs(x), abs(y)) - if abs(x - y) > max(tol["abs"], tol["rel"] * scale): + if not (is_float(xa) and is_float(xb)) or max(len(xa), len(xb)) > MAX_NUMBER_CHARS: + return False, sa # an integer, or a very long number, must match exactly + try: # exact decimal arithmetic: no double-precision blind spot + x, y = decimal.Decimal(xa.decode("ascii")), decimal.Decimal(xb.decode("ascii")) + if not (x.is_finite() and y.is_finite()): + return False, sa + scale, diff = max(abs(x), abs(y)), abs(x - y) + if diff > max(allow_abs, allow_rel * scale): + return False, sa + if scale: + worst = max(worst, float(diff / scale)) + except (ArithmeticError, ValueError): return False, sa differing += 1 - worst = max(worst, abs(x - y) / scale if scale else 0.0) return True, {"differing": differing, "maxRelativeDifference": worst} @@ -338,11 +349,16 @@ def self_check(items): spots = [free[0][0], free[-1][1] - 1, (biggest[0] + biggest[1]) // 2] caught = any(differs_under(flip(p), data, masks, tol) for p in spots) if tol and caught: - # A tolerance must never hide a change to the numbers it covers: flipping the leading digit of a tolerated - # float (one that is not masked) has to be reported, or the tolerance is too loose to prove anything. - floats = [m.start() for m in list(NUMBER.finditer(data[:1 << 20]))[:200] - if is_float(m.group()) and any(a <= m.start() < b for a, b in free)] - caught = not floats or any(differs_under(flip(p), data, masks, tol) for p in floats) + # A tolerance must never hide a change to the numbers it covers: changing the leading digit of every + # sampled float that is not masked has to be reported, or the tolerance is too loose to prove anything. + for m in list(NUMBER.finditer(data[:1 << 20]))[:200]: + token = m.group("num") + if token is None or not is_float(token) or not any(a <= m.start() < b for a, b in free): + continue + at = m.start() + next(i for i, c in enumerate(token) if 48 <= c <= 57) + if not differs_under(flip(at), data, masks, tol): + caught = False + break if not caught: return False, "case %s: a one-byte change to the legacy output was not reported as different%s" % ( cid, " (the tolerance may be too loose)" if tol else "") diff --git a/plugins/code-modernization/scripts/render_rules.py b/plugins/code-modernization/scripts/render_rules.py index b815a2d7..f098a5cf 100644 --- a/plugins/code-modernization/scripts/render_rules.py +++ b/plugins/code-modernization/scripts/render_rules.py @@ -112,7 +112,8 @@ def main(argv): stats = result.get('stats') or {} doc = [f'# Business Rules — {one_line(system, 80)}', '', - f"{len(rules)} confirmed rules ({sum(1 for r in rules if r.get('priority') == 'P0')} P0). " + f"At extraction: {len(rules)} confirmed rules ({sum(1 for r in rules if r.get('priority') == 'P0')} P0); " + f"later steps may add or correct rules below. " f"Each citation was checked by a second agent that read the cited lines; " f"{len(result.get('rejectedRules') or [])} candidate rules were refuted and left out.", '', '| ID | Name | Category | Priority | Source | Confidence |', '|---|---|---|---|---|---|'] diff --git a/plugins/code-modernization/scripts/tests/test_compare_tolerance.py b/plugins/code-modernization/scripts/tests/test_compare_tolerance.py index 5b0841f5..648cc76f 100644 --- a/plugins/code-modernization/scripts/tests/test_compare_tolerance.py +++ b/plugins/code-modernization/scripts/tests/test_compare_tolerance.py @@ -8,6 +8,7 @@ import shutil import sys import tempfile import unittest +from unittest import mock HERE = os.path.dirname(os.path.abspath(__file__)) PLUGIN = os.path.dirname(os.path.dirname(HERE)) @@ -83,14 +84,43 @@ class ToleranceTests(unittest.TestCase): res = self.run_cases([a, b], tolerance=TOL) self.assertEqual([r["verdict"] for r in res["cases"]], ["same", "differs"]) - def test_the_self_check_fails_when_the_tolerance_would_hide_any_change(self): - # every byte is a tolerated float digit and the tolerance is 1%: a one-byte change to a low digit is invisible, - # but the leading-digit change must still be caught, so the check passes here and the outputs still compare - res = self.run_cases([self.case("a", b"5.5\n", b"5.5\n", tolerance={"abs": 100, "why": "absurdly loose"})]) + def test_an_absolute_tolerance_is_capped_like_a_relative_one(self): + for bad in ({"abs": 1e-3, "why": "x"}, {"abs": 100, "why": "x"}): + with self.assertRaises(cmp.InputError, msg=repr(bad)): + self.run_cases([self.case("a", b"5.5\n", b"5.5\n", tolerance=bad)]) + ok = self.run_cases([self.case("a", b"x 0.0000000000000001\n", b"x 0.0\n", tolerance={"abs": 1e-9, "why": "a value that is zero to rounding"})]) + self.assertEqual(ok["cases"][0]["verdict"], "same") + + def test_the_self_check_still_fails_if_a_loose_tolerance_ever_got_through(self): + loose = {"abs": 100, "why": "absurdly loose"} + with mock.patch.object(cmp, "MAX_ABS_TOLERANCE", 1000.0): + res = self.run_cases([self.case("a", b"5.5\n", b"5.5\n", tolerance=loose)]) self.assertFalse(res["selfCheck"]["passed"]) self.assertIn("tolerance may be too loose", res["selfCheck"]["detail"]) self.assertIn("self-check failed", cmp.verdict_of(res)) + def test_dotted_identifiers_are_text_and_must_match_exactly(self): + for legacy, new in ((b"version 1.2.3\n", b"version 1.2.4\n"), (b"host 10.0.0.1\n", b"host 10.0.0.2\n"), + (b"build 2026.09.24 ok\n", b"build 2026.09.25 ok\n")): + res = self.run_cases([self.case("a", legacy, new, tolerance={"rel": 0.01, "why": "test"})]) + self.assertEqual(res["cases"][0]["verdict"], "differs", (legacy, new)) + same = self.run_cases([self.case("a", b"version 1.2.3 total 1.0000000001\n", b"version 1.2.3 total 1.0000000002\n", tolerance=TOL)]) + self.assertEqual(same["cases"][0]["verdict"], "same") + + def test_the_comparison_is_exact_decimal_arithmetic_not_doubles(self): + # 1e-22 apart: equal as doubles, but far outside a declared 1e-30 relative tolerance + tight = {"rel": 1e-30, "why": "essentially exact"} + res = self.run_cases([self.case("a", b"1.0000000000000000000001\n", b"1.0000000000000000000002\n", tolerance=tight)]) + self.assertEqual(res["cases"][0]["verdict"], "differs") + wide = {"rel": 1e-21, "why": "test"} + res = self.run_cases([self.case("a", b"1.0000000000000000000001\n", b"1.0000000000000000000002\n", tolerance=wide)]) + self.assertEqual(res["cases"][0]["verdict"], "same") + + def test_absurd_numbers_do_not_crash_or_pass(self): + for legacy, new in ((b"v 1e999999999999\n", b"v 1e999999999998\n"), (b"v 1." + b"1" * 200 + b"\n", b"v 1." + b"1" * 199 + b"2\n")): + res = self.run_cases([self.case("a", legacy, new, tolerance=TOL)]) + self.assertEqual(res["cases"][0]["verdict"], "differs") + def test_masks_and_tolerance_work_together(self): res = self.run_cases([self.case("a", b"at 2026-09-24 10:00:00 value 2.0000000001\n", b"at 2027-01-01 11:11:11 value 2.0000000002\n", mask=[{"regex": r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d", "why": "run time"}], tolerance=TOL)]) |
