summaryrefslogtreecommitdiff
path: root/plugins/code-modernization/scripts
diff options
context:
space:
mode:
authorMorgan Lunt <morganl@anthropic.com>2026-09-24 21:01:25 -0700
committerMorgan Lunt <morganl@anthropic.com>2026-09-24 21:01:25 -0700
commit2efd715aeb081a965df3b2c871706c3577210e98 (patch)
treeb273a636e0f67c28651f22b2aa96ac2304009648 /plugins/code-modernization/scripts
parent9b4b9865f5e6a07ced1f436972dc76d2c4022749 (diff)
code-modernization: an independent proof step with one verdict per module
/code-modernization:modernize-verify re-checks a finished build instead of trusting the notes it left behind, and a script (not the model) computes one verdict per module: PROVEN, PARTLY PROVEN or NOT PROVEN, with the rules written into the output. The pack re-reads the tests' own result files or a saved runner log (counts the command merely reported never count), traces every P0 business rule to a test that names it, judges the old and new outputs again with compare.py, then runs at least ten inputs that development did not use on both systems. It requires a recorded canary that turned tests red, checks that the legacy source was not touched (by file times: no process runs in the analyzed tree), and lists every human criterion as waiting for a person. For an uplift it diffs the fresh results against the recorded baseline. Verdicts are never carried over from an earlier run. The report gains a Proof section that recomputes each verdict from the same checks, and a failed diagram no longer stops the ones after it from drawing.
Diffstat (limited to 'plugins/code-modernization/scripts')
-rw-r--r--plugins/code-modernization/scripts/baseline_diff.py471
-rw-r--r--plugins/code-modernization/scripts/build_report.py120
-rw-r--r--plugins/code-modernization/scripts/proof_pack.py976
-rw-r--r--plugins/code-modernization/scripts/tests/test_proof_tools.py1368
-rw-r--r--plugins/code-modernization/scripts/trace_rules.py391
5 files changed, 3324 insertions, 2 deletions
diff --git a/plugins/code-modernization/scripts/baseline_diff.py b/plugins/code-modernization/scripts/baseline_diff.py
new file mode 100644
index 00000000..ccbb2713
--- /dev/null
+++ b/plugins/code-modernization/scripts/baseline_diff.py
@@ -0,0 +1,471 @@
+#!/usr/bin/env python3
+"""Compare a fresh test run with the baseline recorded before a same-stack uplift.
+
+ python3 baseline_diff.py <BASELINE.md> --junit DIR_OR_FILE [--junit ...] [--json] [--max-list N]
+
+BASELINE.md (analysis/<system>/BASELINE.md) records how the tests behaved on the OLD version. This
+script reads it and the fresh results, and reports what changed. Nothing is judged by a model.
+
+Baseline, any of these (the most detailed one found is used):
+ a per-test table | Test | Result | one row per test, PASS / FAIL / ERROR / SKIP
+ a per-module table | Module | Pass | Fail | Error | Skip | (the first column may be a module,
+ project or test class; column names are matched, their order does not matter)
+ a totals table | Executed | 946 |, | Passed | 945 |, | Failed | 1 | ...
+ a line target-only: <why the old version could not run here> (nothing to compare)
+
+Fresh results: JUnit-style XML (Maven surefire, Gradle, pytest --junitxml, Ant, jest-junit ...) or
+Visual Studio .trx files. Give a file or a folder; a folder is searched for result files, links are
+never followed, and a file that declares a DTD or entity is refused. A test id is
+"<classname>#<name>"; a repeated id in one file gets a "~N" suffix in document order (the first
+stays plain); the module's own absolute path in a parameterized name is replaced by <MODULE>.
+
+Reported: regressions (passed before, fails now), new failures (a test the baseline never listed),
+tests that still fail as they did, tests that now pass, tests that were skipped and now run, tests
+that no longer run, missing modules, skipped growth and a drop in executed tests. When test names
+drifted inside a class but its counts did not get worse, that is counted as renamed, not missing.
+
+Exit 0 when nothing regressed and something ran; 1 on any regression or new failure, or when no test
+executed; 2 for input that cannot be used. Standard library only.
+"""
+import argparse
+import json
+import os
+import re
+import sys
+from xml.parsers import expat
+
+BAD = ("FAIL", "ERROR")
+MAX_FILE, MAX_FILES, MAX_CASES, MAX_DEPTH, KEEP = 200 << 20, 20000, 2000000, 60, 200
+SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv"}
+STATUS = {"pass": "PASS", "passed": "PASS", "ok": "PASS", "success": "PASS", "green": "PASS", "fail": "FAIL", "failed": "FAIL", "failure": "FAIL",
+ "red": "FAIL", "error": "ERROR", "errors": "ERROR", "errored": "ERROR", "skip": "SKIP", "skipped": "SKIP", "ignored": "SKIP",
+ "pending": "SKIP", "disabled": "SKIP"}
+COLUMNS = (("pass", r"pass|passed|passing|ok|successes?"), ("fail", r"fail|failed|failing|failures?"), ("error", r"errors?|errored"),
+ ("skip", r"skip|skipped|ignored|pending|disabled"))
+TOTALS = {"executed": "executed", "test cases": "cases", "passed": "pass", "pass": "pass", "failed": "fail", "failures": "fail", "errors": "error",
+ "skipped": "skip", "ignored": "skip"}
+
+
+def clean(value, limit=200):
+ text = " ".join(re.sub(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]", " ", str(value if value is not None else "")).split())
+ return text if len(text) <= limit else text[:limit - 1] + "…"
+
+
+class InputError(Exception):
+ pass
+
+
+# ---------------------------------------------------------------- the baseline
+def cell(text):
+ text = text.replace("\\|", "|").strip()
+ if len(text) > 4 and text.startswith("**") and text.endswith("**"):
+ text = text[2:-2].strip()
+ if len(text) >= 2 and text.startswith("`") and text.endswith("`"):
+ text = text[1:-1]
+ return text
+
+
+def split_row(line):
+ s = line.strip()
+ s = s[1:] if s.startswith("|") else s
+ s = s[:-1] if s.endswith("|") and not s.endswith("\\|") else s
+ return [cell(c) for c in re.split(r"(?<!\\)\|", s[:20000])]
+
+
+def join_cut_rows(lines):
+ """A test name that contains a newline cuts its table row in two; put the row back together (at most 3 extra lines)."""
+ out, i = [], 0
+ while i < len(lines):
+ line, extra = lines[i], 0
+ while (line.lstrip().startswith("|") and not line.rstrip().endswith("|") and extra < 3 and i + 1 < len(lines)
+ and lines[i + 1].strip() and not lines[i + 1].lstrip().startswith(("|", "#"))):
+ i += 1
+ extra += 1
+ line += "\n" + lines[i]
+ out.append(line)
+ i += 1
+ return out
+
+
+def md_tables(text):
+ """(nearest heading, header cells, [row cells]) for every pipe table."""
+ lines, heading = join_cut_rows(text.split("\n")), ""
+ i = 0
+ while i < len(lines):
+ h = re.match(r"#{1,6}[ \t]+(.*)", lines[i][:2000])
+ heading = h.group(1) if h else heading
+ if "|" in lines[i] and i + 1 < len(lines) and re.fullmatch(r"\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*", lines[i + 1][:5000]):
+ rows, j = [], i + 2
+ while j < len(lines) and "|" in lines[j] and lines[j].strip():
+ rows.append(split_row(lines[j]))
+ j += 1
+ yield heading, split_row(lines[i]), rows
+ i = j
+ else:
+ i += 1
+
+
+def to_int(text):
+ t = text.strip().replace(",", "")
+ if t in ("", "-", "\u2013", "\u2014"):
+ return 0
+ return int(t) if re.fullmatch(r"\d{1,12}", t) else None
+
+
+def parse_baseline(text):
+ """-> {targetOnly, why, modules {name: counts}, tests {id: status}, totals {name: n}}."""
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
+ m = re.search(r"(?im)^\W*target-only:[ \t]*(.*)$", text)
+ out = {"targetOnly": bool(m), "why": clean(m.group(1), 300) if m else "", "modules": {}, "tests": {}, "totals": {}, "flaky": [], "approved": {}}
+ for heading, header, rows in md_tables(text):
+ low = [h.lower() for h in header]
+ if re.search(r"(?i)flak", heading): # tests the baseline itself says flip on the same version
+ out["flaky"] += [clean(r[0], 400) for r in rows if r and r[0]]
+ continue
+ if re.search(r"(?i)approved", heading): # differences a person accepted: | Test | Reason |
+ for r in rows:
+ if r and r[0]:
+ out["approved"].setdefault(clean(r[0], 400), clean(r[1] if len(r) > 1 else "", 300))
+ continue
+ cols = {key: next((i for i, h in enumerate(low) if re.fullmatch(rx, h)), None) for key, rx in COLUMNS}
+ result = next((i for i, h in enumerate(low) if re.fullmatch(r"result|status|outcome|verdict", h)), None)
+ if cols["pass"] is not None and any(cols[k] is not None for k in ("fail", "error", "skip")):
+ for row in rows:
+ name, nums = row[0] if row else "", {k: to_int(row[i]) if i is not None and i < len(row) else 0 for k, i in cols.items()}
+ if name and not re.fullmatch(r"(?i)totals?|all|sum", name) and None not in nums.values():
+ out["modules"][name[:300]] = nums
+ elif result is not None:
+ name_col = next((i for i, h in enumerate(low) if re.fullmatch(r"tests?|test name|test id|id|name|cases?|test case", h)), 0)
+ for row in rows:
+ status = STATUS.get(row[result].lower()) if result < len(row) else None
+ if status and name_col < len(row) and row[name_col] and result != name_col:
+ out["tests"][row[name_col][:400]] = status
+ elif len(header) >= 2:
+ for row in rows:
+ label, n = (row[0].lower() if row else ""), to_int(row[1]) if len(row) > 1 else None
+ if label in TOTALS and n is not None:
+ out["totals"][TOTALS[label]] = n
+ if not (out["modules"] or out["tests"] or out["totals"]):
+ counts = {}
+ for word, key in (("pass(?:ed|ing)", "pass"), ("fail(?:ed|ing|ures?)", "fail"), ("skipped", "skip"), ("errors?", "error")):
+ hit = re.search(r"(?i)(\d{1,9})\s+(?:tests?\s+|cases?\s+)?" + word, text)
+ if hit:
+ counts[key] = int(hit.group(1))
+ out["totals"] = counts
+ return out
+
+
+def tally(statuses):
+ c = {"pass": 0, "fail": 0, "error": 0, "skip": 0}
+ for s in statuses:
+ c[s.lower()] += 1
+ c["executed"] = c["pass"] + c["fail"] + c["error"]
+ return c
+
+
+def baseline_counts(base):
+ """(counts, where they came from)."""
+ if base["tests"]:
+ return tally(base["tests"].values()), "per-test table"
+ if base["modules"]:
+ c = {k: sum(v[k] for v in base["modules"].values()) for k in ("pass", "fail", "error", "skip")}
+ c["executed"] = c["pass"] + c["fail"] + c["error"]
+ return c, "per-module table"
+ t = base["totals"]
+ if t:
+ c = {k: t.get(k, 0) for k in ("pass", "fail", "error", "skip")}
+ c["executed"] = t["executed"] if "executed" in t else c["pass"] + c["fail"] + c["error"]
+ return c, "totals"
+ return None, "nothing"
+
+
+# ---------------------------------------------------------------- the fresh results
+def refuse(*_):
+ raise ValueError("it declares a DTD or an entity, which test results never do")
+
+
+def parse_results(path):
+ """[(classname, name, status, skip message given, suite name)] from one JUnit or TRX file. Raises ValueError."""
+ cases, suites, cur, depth = [], [], [], [0]
+ trx = {"Passed": "PASS", "Failed": "FAIL", "Error": "ERROR", "Timeout": "ERROR", "Aborted": "ERROR"}
+
+ def start(tag, attrs):
+ depth[0] += 1
+ if depth[0] > MAX_DEPTH:
+ raise ValueError("the XML is nested more than %d levels deep" % MAX_DEPTH)
+ if tag == "testsuite":
+ suites.append(attrs.get("name", "")[:300])
+ elif tag == "testcase":
+ if len(cases) >= MAX_CASES:
+ raise ValueError("more than %d test cases" % MAX_CASES)
+ flag = (attrs.get("status") or attrs.get("result") or "").lower()
+ cur[:] = [(attrs.get("classname") or (suites[-1] if suites else ""))[:300], attrs.get("name", "")[:400],
+ "SKIP" if flag in ("skipped", "ignored", "notrun", "notexecuted", "disabled") else "PASS", False]
+ elif cur and tag in ("failure", "error", "skipped"):
+ if tag == "skipped":
+ cur[3] = bool(attrs.get("message", "").strip())
+ new = {"failure": "FAIL", "error": "ERROR", "skipped": "SKIP"}[tag]
+ if cur[2] == "PASS" or (cur[2] == "SKIP" and new != "SKIP"):
+ cur[2] = new
+ elif tag == "UnitTestResult":
+ name = attrs.get("testName", "")[:400]
+ head, sep, tail = name.partition("(")
+ klass, dot, method = head.rpartition(".")
+ outcome = attrs.get("outcome", "")
+ cases.append((klass[:300] if dot else "", (method + sep + tail) if dot else name, trx.get(outcome, "SKIP"), False, ""))
+
+ def end(tag):
+ depth[0] -= 1
+ if tag == "testcase" and cur:
+ cases.append((cur[0], cur[1], cur[2], cur[3], suites[-1] if suites else ""))
+ cur.clear()
+ elif tag == "testsuite" and suites:
+ suites.pop()
+
+ parser = expat.ParserCreate()
+ parser.StartDoctypeDeclHandler = refuse
+ parser.EntityDeclHandler = refuse
+ parser.StartElementHandler = start
+ parser.EndElementHandler = end
+ try:
+ with open(path, "rb") as fh:
+ parser.ParseFile(fh)
+ except expat.ExpatError as err:
+ raise ValueError("the XML is not well formed (%s)" % expat.ErrorString(err.code))
+ return cases
+
+
+def result_files(paths):
+ """([files], [problems]) from files and folders. Links are never followed."""
+ found, problems = [], []
+ for p in paths:
+ if os.path.isfile(p) and not os.path.islink(p):
+ found.append(p)
+ elif os.path.isdir(p) and not os.path.islink(p):
+ for base, dirs, names in os.walk(p):
+ dirs[:] = [d for d in sorted(dirs) if d not in SKIP_DIRS and not os.path.islink(os.path.join(base, d))]
+ for n in sorted(names):
+ full = os.path.join(base, n)
+ if os.path.islink(full) or not n.lower().endswith((".xml", ".trx")):
+ continue
+ try:
+ with open(full, "rb") as fh:
+ head = fh.read(4096)
+ except OSError:
+ continue
+ if b"<testsuite" in head or b"<TestRun" in head:
+ found.append(full)
+ if len(found) > MAX_FILES:
+ problems.append("More than %d result files were found; the rest were not read." % MAX_FILES)
+ return found[:MAX_FILES], problems
+ else:
+ problems.append("%s is not a file or folder that can be read." % clean(p, 120))
+ return found, problems
+
+
+def module_label(path):
+ """The module folder a Maven or Gradle report belongs to (its parent of target/ or build/), or ''."""
+ parts = os.path.abspath(path).split(os.sep)
+ for i in range(len(parts) - 2, 1, -1):
+ if parts[i] in ("target", "build") and parts[i + 1] in ("surefire-reports", "failsafe-reports", "test-results"):
+ return os.sep.join(parts[:i]) or os.sep
+ return ""
+
+
+def read_results(paths):
+ """-> {tests {id: status}, skipReasons {id: bool}, classes, modules, suites, files, unreadable [str], problems [str], oldest, newest}."""
+ files, problems = result_files(paths)
+ out = {"tests": {}, "skipReasons": {}, "classes": {}, "modules": {}, "suites": {}, "files": 0, "unreadable": [], "problems": problems, "oldest": None, "newest": None}
+ for path in files:
+ label = clean(os.path.basename(path), 100)
+ try:
+ if os.path.getsize(path) > MAX_FILE:
+ raise ValueError("the file is larger than %d MB" % (MAX_FILE >> 20))
+ cases = parse_results(path)
+ except (OSError, ValueError) as err:
+ out["unreadable"].append("%s: %s" % (label, clean(err, 120)))
+ continue
+ root = module_label(path)
+ roots = sorted({root, os.path.realpath(root), root[len("/private"):] if root.startswith("/private/") else root} - {os.sep}, key=len, reverse=True) if root else []
+ seen, mtime = {}, os.path.getmtime(path)
+ out["files"] += 1
+ out["oldest"] = mtime if out["oldest"] is None else min(out["oldest"], mtime)
+ out["newest"] = mtime if out["newest"] is None else max(out["newest"], mtime)
+ for klass, name, status, has_reason, suite in cases:
+ for r in roots:
+ name = name.replace(r, "<MODULE>")
+ name = re.sub(r"(test)\d+(\.tmp)", r"\1<N>\2", name)
+ base = "%s#%s" % (klass, name) if klass else name
+ n = seen.get(base, 0)
+ seen[base] = n + 1
+ tid = base if n == 0 else "%s~%d" % (base, n)
+ out["tests"][tid] = status
+ out["skipReasons"][tid] = has_reason
+ for key, store in ((klass, out["classes"]), (root and os.path.basename(root), out["modules"]), (suite, out["suites"])):
+ if key:
+ store.setdefault(key, []).append(status)
+ for store in ("classes", "modules", "suites"):
+ out[store] = {k: tally(v) for k, v in out[store].items()}
+ return out
+
+
+# ---------------------------------------------------------------- the comparison
+def keep(items):
+ return items[:KEEP]
+
+
+def compare(base, fresh):
+ """-> the report dict (see the module docstring)."""
+ counts_b, source = baseline_counts(base)
+ counts_f = tally(fresh["tests"].values())
+ rep = {"baseline": {"targetOnly": base["targetOnly"], "why": base["why"], "source": source, "counts": counts_b},
+ "fresh": {"files": fresh["files"], "counts": counts_f, "unreadable": fresh["unreadable"][:20], "unreadableCount": len(fresh["unreadable"]),
+ "oldest": fresh["oldest"], "newest": fresh["newest"]},
+ "regressions": [], "flaky": [], "newFailures": [], "stillFailing": [], "fixed": [], "newlySkipped": [], "missing": [], "renamed": 0,
+ "missingModules": [], "moduleDiffs": [], "executedDrop": None, "skippedGrowth": None, "problems": list(fresh["problems"])}
+ bt, ft, flaky = base["tests"], fresh["tests"], set(base.get("flaky", []))
+ if bt:
+ missing = [t for t in bt if t not in ft]
+ added = [t for t in ft if t not in bt]
+ for t, b in bt.items():
+ f = ft.get(t)
+ if f is None:
+ continue
+ if b == "PASS" and f in BAD:
+ (rep["flaky"] if t in flaky else rep["regressions"]).append({"id": t, "before": b, "now": f})
+ elif b in BAD and f in BAD:
+ rep["stillFailing"].append(t)
+ elif b in BAD and f == "PASS":
+ rep["fixed"].append(t)
+ elif b == "PASS" and f == "SKIP":
+ rep["newlySkipped"].append(t)
+ elif b == "SKIP" and f in BAD:
+ rep["newFailures"].append(t)
+ by_class = {}
+ for t in missing:
+ by_class.setdefault(t.split("#", 1)[0], [[], []])[0].append(t)
+ for t in added:
+ by_class.setdefault(t.split("#", 1)[0], [[], []])[1].append(t)
+ drifting = {k for k, (gone, new) in by_class.items() if gone and new}
+ grouped_b, grouped_f = {}, {}
+ for src, dst in ((bt, grouped_b), (ft, grouped_f)):
+ for t, v in src.items():
+ if t.split("#", 1)[0] in drifting:
+ dst.setdefault(t.split("#", 1)[0], []).append(v)
+ for klass, (gone, new) in by_class.items():
+ b_counts, f_counts = tally(grouped_b.get(klass, [])), tally(grouped_f.get(klass, []))
+ if gone and new and f_counts["executed"] >= b_counts["executed"] and f_counts["fail"] + f_counts["error"] <= b_counts["fail"] + b_counts["error"]:
+ rep["renamed"] += len(gone)
+ else:
+ rep["missing"] += gone
+ rep["newFailures"] += [t for t in new if ft[t] in BAD]
+ for name, b in base["modules"].items():
+ f = fresh["classes"].get(name) or fresh["modules"].get(name) or fresh["suites"].get(name)
+ if f is None:
+ rep["missingModules"].append(name)
+ continue
+ problems = []
+ if f["executed"] < b["pass"] + b["fail"] + b["error"]:
+ problems.append("%d test(s) executed, %d before" % (f["executed"], b["pass"] + b["fail"] + b["error"]))
+ if f["skip"] > b["skip"]:
+ problems.append("%d skipped, %d before" % (f["skip"], b["skip"]))
+ if not bt and f["fail"] + f["error"] > b["fail"] + b["error"]:
+ rep["regressions"].append({"id": name + " (all its tests)", "before": "%d failing" % (b["fail"] + b["error"]), "now": "%d failing" % (f["fail"] + f["error"])})
+ if problems:
+ rep["moduleDiffs"].append({"module": name, "problems": problems})
+ if counts_b:
+ if counts_f["executed"] < counts_b["executed"]:
+ rep["executedDrop"] = {"before": counts_b["executed"], "now": counts_f["executed"]}
+ if counts_f["skip"] > counts_b["skip"]:
+ rep["skippedGrowth"] = {"before": counts_b["skip"], "now": counts_f["skip"]}
+ rep["approved"] = []
+ for key, label in (("regressions", "passed before, fails now"), ("newFailures", "not in the baseline, fails now")):
+ kept = []
+ for item in rep[key]:
+ tid = item["id"] if isinstance(item, dict) else item
+ if tid in base.get("approved", {}):
+ rep["approved"].append({"id": tid, "reason": base["approved"][tid], "was": label})
+ else:
+ kept.append(item)
+ rep[key] = kept
+ for key in ("regressions", "flaky", "newFailures", "stillFailing", "fixed", "newlySkipped", "missing", "missingModules", "moduleDiffs", "approved"):
+ rep[key + "Count"], rep[key] = len(rep[key]), keep(rep[key])
+ rep["ok"] = counts_f["executed"] > 0 and not rep["regressionsCount"] and not rep["newFailuresCount"]
+ return rep
+
+
+def render(rep, limit=10):
+ b, f = rep["baseline"]["counts"], rep["fresh"]["counts"]
+ show = lambda c: "%d executed (%d pass, %d fail, %d error, %d skip)" % (c["executed"], c["pass"], c["fail"], c["error"], c["skip"]) # noqa: E731
+ lines = ["baseline (%s): %s" % (rep["baseline"]["source"], show(b) if b else "nothing readable"),
+ "this run (%d result file(s)): %s" % (rep["fresh"]["files"], show(f))]
+ if rep["baseline"]["targetOnly"]:
+ lines.append("BASELINE.md says target-only (%s): there is no old-version result to compare with." % (rep["baseline"]["why"] or "no reason given"))
+
+ def block(title, key, fmt=lambda x: clean(x, 160)):
+ if rep[key + "Count"]:
+ lines.append("%s: %d" % (title, rep[key + "Count"]))
+ lines.extend(" " + fmt(x) for x in rep[key][:limit])
+ if rep[key + "Count"] > limit:
+ lines.append(" ... and %d more (use --json)" % (rep[key + "Count"] - limit))
+ else:
+ lines.append("%s: 0" % title)
+ block("regressions (passed before, fail now)", "regressions", lambda x: "%s: %s -> %s" % (clean(x["id"], 140), x["before"], x["now"]))
+ block("differences a person approved in BASELINE.md (not counted)", "approved", lambda x: "%s: %s (%s)" % (clean(x["id"], 120), x["was"], clean(x["reason"], 100)))
+ block("flaky flips the baseline lists (not counted)", "flaky", lambda x: "%s: %s -> %s" % (clean(x["id"], 140), x["before"], x["now"]))
+ block("new failures (not in the baseline)", "newFailures")
+ block("still failing, as in the baseline", "stillFailing")
+ block("now passing (failed before)", "fixed")
+ block("skipped now that ran before", "newlySkipped")
+ block("baseline tests that did not run", "missing")
+ block("modules missing from this run", "missingModules")
+ block("modules with fewer tests or more skips", "moduleDiffs", lambda x: "%s: %s" % (clean(x["module"], 100), "; ".join(x["problems"])))
+ if rep["renamed"]:
+ lines.append("renamed: %d test name(s) changed but their class did not get worse" % rep["renamed"])
+ if rep["executedDrop"]:
+ lines.append("executed tests dropped from %(before)d to %(now)d" % rep["executedDrop"])
+ if rep["skippedGrowth"]:
+ lines.append("skipped tests grew from %(before)d to %(now)d" % rep["skippedGrowth"])
+ lines += ["%d result file(s) could not be read: %s" % (rep["fresh"]["unreadableCount"], "; ".join(rep["fresh"]["unreadable"][:3])) if rep["fresh"]["unreadableCount"] else "all result files were read"]
+ lines += rep["problems"]
+ lines.append("OK: nothing regressed and %d test(s) executed" % f["executed"] if rep["ok"] else "NOT OK: %s" % (
+ "no test executed" if not f["executed"] else "%d regression(s), %d new failure(s)" % (rep["regressionsCount"], rep["newFailuresCount"])))
+ return "\n".join(lines)
+
+
+def run(baseline_path, paths):
+ """-> the report. Raises InputError for a baseline or results that cannot be used."""
+ if os.path.islink(baseline_path):
+ raise InputError("%s is a symbolic link" % baseline_path)
+ try:
+ with open(baseline_path, "rb") as fh:
+ text = fh.read(16 << 20).decode("utf-8", "replace")
+ except OSError as err:
+ raise InputError("cannot read %s: %s" % (baseline_path, err.__class__.__name__))
+ base = parse_baseline(text)
+ if not (base["targetOnly"] or base["modules"] or base["tests"] or base["totals"]):
+ raise InputError("%s has no per-test table, per-module table, totals or target-only line that can be read" % baseline_path)
+ return compare(base, read_results(paths))
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description="Compare a fresh test run with BASELINE.md.")
+ ap.add_argument("baseline", help="analysis/<system>/BASELINE.md")
+ ap.add_argument("--junit", "--trx", action="append", default=[], metavar="PATH", help="a results file or a folder to search (repeat for several)")
+ ap.add_argument("--json", action="store_true", help="print the full report as JSON")
+ ap.add_argument("--max-list", type=int, default=10, help="how many entries to print per list (default 10)")
+ args = ap.parse_args(argv)
+ if not args.junit:
+ print("baseline_diff.py: give at least one --junit file or folder", file=sys.stderr)
+ return 2
+ try:
+ rep = run(args.baseline, args.junit)
+ except InputError as err:
+ print("baseline_diff.py: %s" % err, file=sys.stderr)
+ return 2
+ print(json.dumps(rep, indent=1, ensure_ascii=True) if args.json else render(rep, max(1, args.max_list)))
+ return 0 if rep["ok"] else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/code-modernization/scripts/build_report.py b/plugins/code-modernization/scripts/build_report.py
index c6c58c66..06e97b44 100644
--- a/plugins/code-modernization/scripts/build_report.py
+++ b/plugins/code-modernization/scripts/build_report.py
@@ -35,7 +35,7 @@ STEPS = [("preflight", "Preflight"), ("assess", "Assess"), ("map", "Map"), ("rul
TITLES = [("overview", "Overview"), ("assessment", "Assessment"), ("diagrams", "Diagrams"),
("rules", "Business rules"), ("brief", "Brief"), ("security", "Security"),
("delta", "Delta catalog & baseline"), ("spec", "Spec & architecture"),
- ("build", "Build notes"), ("equivalence", "Equivalence")]
+ ("build", "Build notes"), ("proof", "Proof"), ("equivalence", "Equivalence")]
DOCS = [("overview", ["PREFLIGHT.md"]), ("assessment", ["ASSESSMENT.md"]),
("rules", ["BUSINESS_RULES.md", "RULE_REVIEWS.md", "DATA_OBJECTS.md"]), ("brief", ["MODERNIZATION_BRIEF.md"]),
("security", ["SECURITY_FINDINGS.md"]), ("delta", ["DELTA_CATALOG.md", "BASELINE.md", "PLAYBOOK.md"]),
@@ -318,6 +318,113 @@ def equivalence_view(obj):
"legacy": endpoint(obj.get("legacy")), "new": endpoint(obj.get("new")), "cases": rows[:MAX_CASES], "cut": max(0, len(rows) - MAX_CASES)}
+# ---------------------------------------------------------------- the proof pack (VERIFICATION.json)
+PROOF_VERDICTS = ("PROVEN", "PARTLY PROVEN", "NOT PROVEN")
+PROOF_CHECKS = (("tests", "Tests ran"), ("rules", "Rules traced"), ("same", "Same behavior"), ("fresh", "Fresh inputs"), ("canary", "Canary"), ("source", "Source untouched"))
+RULE_STATES = ("tested", "claimed only", "code only", "none")
+FRESH_NEEDED = 10
+
+
+def text_of(value, limit=300):
+ return value[:limit] if isinstance(value, str) else ""
+
+
+def count_of(value):
+ return value if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 10 ** 9 else 0
+
+
+def texts_of(value, limit=300, cap=40):
+ return [v[:limit] for v in value[:cap] if isinstance(v, str)] if isinstance(value, list) else []
+
+
+def num_of(value):
+ return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and value == value and abs(value) < 1e300 else 0.0
+
+
+def tolerances_of(obj):
+ return [{"why": text_of(t.get("why"), 200), "rel": num_of(t.get("rel")), "abs": num_of(t.get("abs")), "cases": count_of(t.get("cases"))}
+ for t in (obj.get("tolerances") if isinstance(obj, dict) and isinstance(obj.get("tolerances"), list) else [])[:10] if isinstance(t, dict)]
+
+
+def counts_of(obj, keys):
+ obj = obj if isinstance(obj, dict) else {}
+ return {k: count_of(obj.get(k)) for k in keys}
+
+
+def proof_module(m, problems):
+ """One module of VERIFICATION.json, made safe, with its verdict recomputed from its own checks: the file's word is never taken."""
+ name = text_of(m.get("name"), 120) or "(unnamed)"
+ ev = m["evidence"] if isinstance(m.get("evidence"), dict) else {}
+ by_id = {}
+ for c in (m["checks"] if isinstance(m.get("checks"), list) else [])[:20]:
+ if isinstance(c, dict) and c.get("id") in dict(PROOF_CHECKS) and c.get("state") in ("pass", "gap", "fail", "na") and c["id"] not in by_id:
+ by_id[c["id"]] = {"id": c["id"], "label": dict(PROOF_CHECKS)[c["id"]], "state": c["state"], "detail": text_of(c.get("detail"), 700)}
+ tests = counts_of(ev.get("tests"), ("executed", "failed", "skipped"))
+ rules = ev["rules"] if isinstance(ev.get("rules"), dict) else None
+ p0 = [{"id": text_of(r.get("id"), 40), "name": text_of(r.get("name"), 200), "confidence": text_of(r.get("confidence"), 10),
+ "status": r.get("status") if r.get("status") in RULE_STATES else "none", "tests": count_of(r.get("tests")), "main": count_of(r.get("main")), "where": text_of(r.get("where"), 200)}
+ for r in (rules["p0"] if rules and isinstance(rules.get("p0"), list) else [])[:200] if isinstance(r, dict)]
+ fresh = dict(counts_of(ev.get("fresh"), ("inputs", "executed", "same", "differs", "missing", "withinTolerance")), tolerances=tolerances_of(ev.get("fresh"))) if isinstance(ev.get("fresh"), dict) else None
+ eq = ev.get("equivalence") if isinstance(ev.get("equivalence"), dict) else None
+ notes = []
+ for cid, label in PROOF_CHECKS: # a pack that leaves a check out cannot be PROVEN
+ if cid not in by_id:
+ by_id[cid] = {"id": cid, "label": label, "state": "gap", "detail": "This check is missing from VERIFICATION.json."}
+ notes.append("the %s check is missing" % label.lower())
+ if by_id["tests"]["state"] == "pass" and tests["executed"] == 0:
+ by_id["tests"].update(state="fail", detail="No test executed, whatever the file says.")
+ notes.append("it says tests passed but none executed")
+ if by_id["rules"]["state"] == "pass" and any(r["status"] != "tested" for r in p0):
+ by_id["rules"].update(state="gap", detail="Some P0 rules are not named by a test, whatever the file says.")
+ notes.append("it says every P0 rule is tested but the table shows otherwise")
+ if by_id["fresh"]["state"] == "pass" and (fresh is None or fresh["inputs"] < FRESH_NEEDED):
+ by_id["fresh"].update(state="gap", detail="Fewer than %d fresh inputs are recorded, whatever the file says." % FRESH_NEEDED)
+ notes.append("it says the fresh-input check passed with fewer than %d inputs" % FRESH_NEEDED)
+ for cid, bad in (("same", eq), ("fresh", fresh)): # a pass cannot stand next to differing or missing cases
+ if by_id[cid]["state"] == "pass" and isinstance(bad, dict) and (count_of(bad.get("differs")) or count_of(bad.get("missing"))):
+ by_id[cid].update(state="fail", detail="Some cases differ or are missing, whatever the file says.")
+ notes.append("it says %s passed but cases differ or are missing" % by_id[cid]["label"].lower())
+ if by_id["tests"]["state"] == "pass" and tests["failed"] and text_of(m.get("track"), 20) != "uplift":
+ by_id["tests"].update(state="fail", detail="Some tests failed, whatever the file says.")
+ notes.append("it says tests passed but some failed")
+ checks = [by_id[cid] for cid, _ in PROOF_CHECKS]
+ states = {c["state"] for c in checks}
+ verdict = "NOT PROVEN" if "fail" in states else "PARTLY PROVEN" if "gap" in states else "PROVEN"
+ if m.get("verdict") in PROOF_VERDICTS and m.get("verdict") != verdict or notes:
+ problems.append("%s: the file recorded %s; its own evidence gives %s, so %s is shown%s." % (
+ name, text_of(m.get("verdict"), 20) or "no verdict", verdict, verdict, " (" + "; ".join(notes) + ")" if notes else ""))
+ base = ev.get("baseline") if isinstance(ev.get("baseline"), dict) else None
+ brief = m["brief"] if isinstance(m.get("brief"), dict) else {}
+ items = [{"text": text_of(i.get("text"), 300), "where": text_of(i.get("where"), 80)} for i in (brief.get("items") if isinstance(brief.get("items"), list) else [])[:40] if isinstance(i, dict)]
+ return {"name": name, "track": text_of(m.get("track"), 20), "verdict": verdict, "verifiedAt": text_of(m.get("verifiedAt"), 40), "checks": checks,
+ "reasons": ["%s: %s" % (c["label"], c["detail"]) for c in checks if c["state"] in ("fail", "gap")], "passed": ["%s: %s" % (c["label"], c["detail"]) for c in checks if c["state"] == "pass"],
+ "tests": tests, "hasRules": rules is not None, "p0": p0,
+ "p0Counts": {"tested": sum(1 for r in p0 if r["status"] == "tested"), "claimedOnly": sum(1 for r in p0 if r["status"] == "claimed only"), "none": sum(1 for r in p0 if r["status"] not in ("tested", "claimed only"))},
+ "equivalence": dict(counts_of(eq, ("cases", "executed", "same", "differs", "missing", "withinTolerance")), tolerances=tolerances_of(eq), approved=[{"id": text_of(a.get("id"), 80), "why": text_of(a.get("why"), 300)} for a in (eq.get("approved") if isinstance(eq.get("approved"), list) else [])[:20] if isinstance(a, dict)],
+ masks=[{"why": text_of(k.get("why"), 200), "cases": count_of(k.get("cases"))} for k in (eq.get("masks") if isinstance(eq.get("masks"), list) else [])[:10] if isinstance(k, dict)]) if eq else None,
+ "fresh": fresh, "baseline": counts_of(base, ("regressionsCount", "newFailuresCount", "fixedCount", "missingCount", "renamed")) if base else None,
+ "canary": [{"change": text_of(c.get("change"), 200), "testsFailed": count_of(c.get("testsFailed")), "shown": c.get("shown") is True} for c in (ev.get("canary") if isinstance(ev.get("canary"), list) else [])[:10] if isinstance(c, dict)],
+ "notProven": texts_of(m.get("notProven"), 400, 12), "needsPerson": texts_of(m.get("needsPerson"), 300, 10), "caveats": texts_of(m.get("caveats"), 400, 20),
+ "people": items, "peopleCount": max(count_of(brief.get("count")), len(items)), "briefFound": brief.get("found") is True}
+
+
+def proof_view(obj):
+ """VERIFICATION.json as the page uses it, or None when it is not a proof pack. Every module's verdict is recomputed from its checks."""
+ if not isinstance(obj, dict) or not isinstance(obj.get("modules"), list):
+ return None
+ problems = texts_of(obj.get("problems"), 300, 10)
+ mods = [proof_module(m, problems) for m in obj["modules"][:100] if isinstance(m, dict)]
+ counts = {v: sum(1 for m in mods if m["verdict"] == v) for v in PROOF_VERDICTS}
+ verdict = "NOT PROVEN" if counts["NOT PROVEN"] or not mods else "PARTLY PROVEN" if counts["PARTLY PROVEN"] else "PROVEN"
+ lg = obj["legacy"] if isinstance(obj.get("legacy"), dict) else {}
+ so = obj["signoff"] if isinstance(obj.get("signoff"), dict) else {}
+ headline = "Proof: %s (%d module%s)." % (", ".join("%d %s" % (counts[v], v) for v in PROOF_VERDICTS if counts[v]) or "no module was verified", len(mods), "" if len(mods) == 1 else "s")
+ return {"generated": text_of(obj.get("generated"), 40), "verdict": verdict, "counts": counts, "headline": headline, "problems": problems, "modules": mods,
+ "legacy": {"path": text_of(lg.get("path"), 200), "target": text_of(lg.get("target"), 300), "ran": lg.get("ran") if isinstance(lg.get("ran"), bool) else None,
+ "state": text_of(lg.get("state"), 20), "detail": text_of(lg.get("detail"), 300)},
+ "rules": texts_of(obj.get("rules"), 700, 12), "signoff": {k: text_of(so.get(k), 120) for k in ("name", "role", "date", "decision")}}
+
+
# ---------------------------------------------------------------- assembling the report
def nonempty_dir(p):
try:
@@ -381,7 +488,7 @@ def build(system, workspace, out=None):
parts, texts, docs = {k: [] for k, _ in TITLES}, [], {}
reviews, _ = src.json(a("RULE_REVIEWS.json"), "RULE_REVIEWS.json")
reviews = {k: v for k, v in reviews["reviews"].items() if isinstance(v, dict)} if isinstance(reviews, dict) and isinstance(reviews.get("reviews"), dict) else {}
- glance = {"rules": None, "security": None, "baseline": None, "topology": None, "equivalence": None}
+ glance = {"rules": None, "security": None, "baseline": None, "topology": None, "equivalence": None, "proof": None}
for key, names in DOCS:
for name in names:
@@ -439,6 +546,15 @@ def build(system, workspace, out=None):
glance["equivalence"] = {"state": "red", "headline": "EQUIVALENCE.json could not be used, so equivalence is not proven.", "problems": [], "tally": None}
parts["equivalence"].append({"t": "p", "text": glance["equivalence"]["headline"]})
+ ver, ver_seen = src.json(a("VERIFICATION.json"), "VERIFICATION.json")
+ if ver_seen:
+ pv = proof_view(ver)
+ if pv:
+ parts["proof"].append({"t": "proof", "proof": pv})
+ glance["proof"] = {"verdict": pv["verdict"], "headline": pv["headline"], "counts": pv["counts"], "problems": pv["problems"][:3], "modules": [{"name": m["name"], "verdict": m["verdict"]} for m in pv["modules"][:8]]}
+ else:
+ glance["proof"] = {"verdict": "NOT PROVEN", "headline": "VERIFICATION.json could not be used, so nothing is proven.", "counts": {}, "problems": [], "modules": []}
+ parts["proof"].append({"t": "p", "text": glance["proof"]["headline"]})
mods = [os.path.join(src.mdir, system + s) for s in ("", "-uplifted", "-reimagined")]
done = {"preflight": "PREFLIGHT.md" in docs, "assess": "ASSESSMENT.md" in docs, "rules": "BUSINESS_RULES.md" in docs, "brief": "MODERNIZATION_BRIEF.md" in docs,
"map": topo is not None or has_map or any(f["name"] != "ARCHITECTURE.mmd" for f in figures), "build": any(nonempty_dir(p) for p in mods), "harden": "SECURITY_FINDINGS.md" in docs}
diff --git a/plugins/code-modernization/scripts/proof_pack.py b/plugins/code-modernization/scripts/proof_pack.py
new file mode 100644
index 00000000..33838d34
--- /dev/null
+++ b/plugins/code-modernization/scripts/proof_pack.py
@@ -0,0 +1,976 @@
+#!/usr/bin/env python3
+"""Independent proof pack: one plain verdict per built module, computed from the evidence files.
+
+ python3 proof_pack.py <system> [module] [--workspace DIR]
+
+Writes analysis/<system>/VERIFICATION.md (for people) and VERIFICATION.json (for the report). The
+verdict is computed here by fixed rules, never by a model's opinion, and every rule is written into
+the output so an auditor can follow it:
+
+ PROVEN all six checks below pass.
+ NOT PROVEN any check fails: nothing executed, a test failed, an equivalence case differs or is
+ missing, a baseline regression or new failure, a deliberate break that no test noticed.
+ PARTLY PROVEN nothing failed, but at least one check could not be passed; each is listed.
+
+ 1 Tests ran at least one test executed in a fresh run, none failed, none was skipped
+ without a reason, and every result file is newer than the code. The counts must
+ come from files this script parsed itself: JUnit-style XML, or a saved raw runner
+ log (Maven/Gradle, cargo, pytest, unittest, go test, dotnet test, jest, vitest,
+ ctest, phpunit). Counts only typed into test-runs.json cap the check at "gap".
+ 2 Rules traced rewrite and reimagine only: every P0 rule the module answers for is named by a
+ test (an id in a test name or comment). A rule only the notes name is "claimed",
+ not tested. Uplifts keep the code, so they trace no rules.
+ 3 Same behavior the development cases, judged again here by compare.py, executed at least one
+ case with none differing or missing (a case a person approved is allowed and
+ listed); for an uplift, baseline_diff.py may stand in: no regression, no new
+ failure, no missing test or module, no drop in executed tests.
+ 4 Fresh inputs at least 10 new inputs, none with the same output as a development case, ran on
+ the legacy and the new code and compare.py finds no difference. Needed whenever
+ the legacy could run here; when it could not, the proof rests on recorded
+ traces and the best possible verdict is PARTLY PROVEN.
+ 5 Canary a deliberate one-line break whose own result file or saved runner log, parsed
+ here, shows failing tests. A "Canary:" line in the notes is a claim, not evidence.
+ 6 Source untouched no file under legacy/<system> is newer than the analysis (PREFLIGHT.md); a plain
+ file walk, no version-control tool is run inside the untrusted tree.
+
+Open questions, unticked criteria and the sign-off are for a person: they never change the verdict.
+
+Evidence read (under analysis/<system>/, or as named): equivalence/test-runs.json (written by the
+modernize-verify command), equivalence/[<module>/]cases.json and fresh-cases.json (judged again here,
+not read from EQUIVALENCE.json), BASELINE.md, BUSINESS_RULES.md with the code under modernized/,
+MODERNIZATION_BRIEF.md, the notes files, and legacy/<system>. Everything read is untrusted text: it is
+never run, links out of the workspace are refused, sizes are capped. Exit 0 when every verdict is
+PROVEN, 1 when not, 2 for input that cannot be used.
+"""
+import argparse
+import datetime
+import json
+import os
+import re
+import stat
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.dont_write_bytecode = True # importing the sibling scripts must not leave __pycache__ in the plugin folder
+sys.path.insert(0, HERE)
+import baseline_diff # noqa: E402
+import compare # noqa: E402
+import trace_rules # noqa: E402
+
+FRESH_MIN, LIST_CAP, JSON_CAP = 10, 40, 8 << 20
+VERDICTS = ("PROVEN", "PARTLY PROVEN", "NOT PROVEN")
+CHECKS = (("tests", "Tests ran"), ("rules", "Rules traced"), ("same", "Same behavior"), ("fresh", "Fresh inputs"),
+ ("canary", "Canary"), ("source", "Source untouched"))
+RULES_TEXT = (
+ "PROVEN needs all six checks to pass. NOT PROVEN when any check fails. PARTLY PROVEN when nothing failed but a check could not pass.",
+ "1. Tests ran: at least one test executed in a fresh run, none failed, none was skipped without a reason, and every result file is newer than the code. "
+ "The counts must be read by this script from result files or a saved raw runner log; counts only typed in cannot reach PROVEN.",
+ "2. Rules traced (rewrite and reimagine): every P0 rule the module answers for is named by at least one test. A rule that only the notes name is claimed, not tested.",
+ "3. Same behavior: the development cases, judged again by compare.py, executed at least one case and none differs or is missing (a difference a person approved is allowed and listed); "
+ "for an uplift, no regression, no new failure, no missing test and no drop in executed tests against BASELINE.md.",
+ "4. Fresh inputs: at least 10 new inputs, none with the same output as a development case, ran on the legacy and the new code with no difference. Needed whenever the legacy could run here; "
+ "when it could not, the proof is trace-based and the best verdict is PARTLY PROVEN.",
+ "5. Canary: a deliberate one-line break whose own result file or saved runner log shows failing tests. A line in the notes is a claim.",
+ "6. Source untouched: no file under legacy/<system> is newer than the analysis (PREFLIGHT.md), by a plain file walk; no version-control tool is run.",
+ "Open questions, unticked criteria and the sign-off are for a person. They never change the verdict.",
+)
+WORDS = {"pass": "pass", "gap": "not proven", "fail": "FAIL", "na": "not applicable"}
+CANARY = re.compile(r"Canary[^:\n|]{0,20}:\s*(.{1,300}?)\s*(?:→|->|=>|,)\s*(\d[\d,]*)\s+tests?\s+(?:failed|went red|failing)", re.I)
+CHECKBOX = re.compile(r"^\s*[-*]\s*\[( |x|X)\]\s*(.*)$")
+NOTE_NAMES = trace_rules.NOTES_NAMES
+clean = trace_rules.clean
+
+
+class InputError(Exception):
+ pass
+
+
+# ---------------------------------------------------------------- reading evidence safely
+def read_json(path, cap=8 << 20):
+ """-> (value, problem). A missing file is (None, None); a link, a huge file or bad JSON is (None, reason)."""
+ try:
+ st = os.lstat(path)
+ except OSError:
+ return None, None
+ name = clean(os.path.basename(path), 80)
+ if not stat.S_ISREG(st.st_mode):
+ return None, "%s is a link or not a regular file, so it was not read" % name
+ if st.st_size > cap:
+ return None, "%s is larger than %d MB, so it was not read" % (name, cap >> 20)
+ try:
+ with open(path, "rb") as fh:
+ return json.loads(fh.read().decode("utf-8-sig")), None
+ except (OSError, ValueError, RecursionError) as err:
+ return None, "%s could not be read as JSON (%s)" % (name, clean(str(err), 80))
+
+
+def read_text(path, cap=8 << 20):
+ """Text of a regular, non-binary file, or None."""
+ return trace_rules.read_text(path, cap) if os.path.isfile(path) and not os.path.islink(path) else None
+
+
+def nint(value):
+ return value if isinstance(value, int) and not isinstance(value, bool) and 0 <= value <= 10 ** 9 else None
+
+
+def inside(workspace, rel):
+ """The real path of `rel` when it stays inside the workspace, else None (absolute paths and links out are refused)."""
+ if not isinstance(rel, str) or not rel or "\x00" in rel:
+ return None
+ real = os.path.realpath(rel if os.path.isabs(rel) else os.path.join(workspace, rel))
+ root = os.path.realpath(workspace)
+ try:
+ return real if os.path.commonpath([root, real]) == root else None
+ except ValueError:
+ return None
+
+
+# ---------------------------------------------------------------- test-runs.json
+def load_test_runs(adir):
+ """-> the validated content of equivalence/test-runs.json (everything defaulted when it is absent or malformed)."""
+ obj, problem = read_json(os.path.join(adir, "equivalence", "test-runs.json"))
+ out = {"present": isinstance(obj, dict), "problems": [problem] if problem else [], "date": "", "legacy": {"ran": None, "how": "", "why": ""}, "suites": [], "canaries": [], "leftOut": []}
+ if not isinstance(obj, dict):
+ if obj is not None:
+ out["problems"].append("test-runs.json is not a JSON object, so it was not used.")
+ return out
+ out["date"] = clean(obj.get("date"), 40)
+ out["leftOut"] = [clean(v, 200) for v in (obj.get("leftOut") if isinstance(obj.get("leftOut"), list) else [])[:20] if isinstance(v, str) and v.strip()]
+ lg = obj.get("legacy") if isinstance(obj.get("legacy"), dict) else {}
+ out["legacy"] = {"ran": lg.get("ran") if isinstance(lg.get("ran"), bool) else None, "how": clean(lg.get("how"), 300), "why": clean(lg.get("why"), 300)}
+ for s in (obj.get("suites") if isinstance(obj.get("suites"), list) else [])[:200]:
+ if isinstance(s, dict):
+ out["suites"].append({"module": clean(s.get("module"), 100), "name": clean(s.get("name"), 120), "command": clean(s.get("command"), 300), "date": clean(s.get("date"), 40),
+ "executed": nint(s.get("executed")), "failed": nint(s.get("failed")), "skipped": nint(s.get("skipped")),
+ "skippedReason": clean(s.get("skippedReason"), 300), "note": clean(s.get("note"), 300), "junit": paths_of(s.get("junit")), "log": paths_of(s.get("log"))})
+ for c in (obj.get("canaries") if isinstance(obj.get("canaries"), list) else [])[:50]:
+ if isinstance(c, dict):
+ out["canaries"].append({"module": clean(c.get("module"), 100), "change": clean(c.get("change"), 300), "testsFailed": nint(c.get("testsFailed")),
+ "junit": paths_of(c.get("junit")), "log": paths_of(c.get("log"))})
+ return out
+
+
+def paths_of(value):
+ """A list of path strings from a string or a list, however malformed."""
+ return [v for v in (value if isinstance(value, list) else [value])[:20] if isinstance(v, str) and v]
+
+
+def suites_for(runs, subject, unit, subjects):
+ """The suites that belong to one subject. A suite that names no module belongs to the only subject."""
+ others = {s["name"].lower() for s in subjects if s["track"] != "uplift"}
+ out = []
+ for s in runs["suites"]:
+ mod = s["module"].lower()
+ if not mod:
+ ok = len(subjects) == 1
+ elif subject["track"] == "uplift": # one uplifted working copy holds many units; a unit argument narrows it
+ ok = mod not in others and (not unit or mod == unit.lower() or mod == subject["name"].lower())
+ else:
+ ok = mod == subject["name"].lower()
+ if ok:
+ out.append(s)
+ return out
+
+
+def code_mtime(root):
+ """Newest modification time among a module's code (no build output, hidden files or documents)."""
+ newest = 0.0
+ for base, dirs, names in os.walk(root):
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d not in trace_rules.SKIP_DIRS and not os.path.islink(os.path.join(base, d))]
+ for n in names:
+ full = os.path.join(base, n)
+ if n.startswith(".") or os.path.splitext(n)[1].lower() in trace_rules.DOC_EXT:
+ continue
+ try:
+ st = os.lstat(full)
+ except OSError:
+ continue
+ if stat.S_ISREG(st.st_mode):
+ newest = max(newest, st.st_mtime)
+ return newest
+
+
+# ---------------------------------------------------------------- raw runner logs
+LOG_CAP, LOG_LINE = 16 << 20, 2000
+NUM_WORD = re.compile(r"(\d+)\s+([A-Za-z]+)")
+
+
+def words(text):
+ """{'passed': 10, 'failed': 2} from '2 failed, 10 passed' style text."""
+ out = {}
+ for n, w in NUM_WORD.findall(text[:LOG_LINE]):
+ out[w.lower()] = out.get(w.lower(), 0) + int(n)
+ return out
+
+
+def _maven(m):
+ run, f, e, sk = (int(g) for g in m.groups())
+ return max(0, run - f - e - sk), f + e, sk
+
+
+def _pytest(m):
+ w = words(m.group(1))
+ return w.get("passed", 0) + w.get("xpassed", 0) + w.get("xfailed", 0), w.get("failed", 0) + w.get("error", 0) + w.get("errors", 0), w.get("skipped", 0)
+
+
+def _jest(m):
+ w = words(m.group(1))
+ return w.get("passed", 0), w.get("failed", 0), w.get("skipped", 0)
+
+
+def _php(m):
+ w = {k.lower(): int(v) for k, v in re.findall(r"([A-Za-z]+):\s*(\d+)", m.group(1)[:LOG_LINE])}
+ failed, skipped = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0) + w.get("incomplete", 0)
+ return max(0, w.get("tests", 0) - failed - skipped), failed, skipped
+
+
+def _ctest(m):
+ failed, total = int(m.group(1)), int(m.group(2))
+ return max(0, total - failed), failed, 0
+
+
+def _gradle(m):
+ total, failed, skipped = int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
+ return max(0, total - failed - skipped), failed, skipped
+
+
+# runner, a line pattern, and how to read (passed, failed, skipped) from a match. Every pattern is anchored and bounded.
+LOG_LINES = (
+ ("maven", re.compile(r"^(?:\[\w+\]\s*)?Tests run: (\d+), Failures: (\d+), Errors: (\d+), Skipped: (\d+)\s*$"), _maven),
+ ("gradle", re.compile(r"^(\d+) tests? completed(?:, (\d+) failed)?(?:, (\d+) skipped)?\s*$"), _gradle),
+ ("cargo", re.compile(r"^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed; (\d+) ignored;"), lambda m: (int(m.group(1)), int(m.group(2)), int(m.group(3)))),
+ ("pytest", re.compile(r"^(?:=+ )?((?:\d+ [a-z]+(?:, )?)+) in [\d.]+s(?: \([\d:]+\))?(?: =+)?\s*$"), _pytest),
+ ("pytest", re.compile(r"^(?:=+ )?no tests ran in [\d.]+s"), lambda m: (0, 0, 0)),
+ ("go test", re.compile(r"^\s*--- (PASS|FAIL|SKIP): \S"), lambda m: {"PASS": (1, 0, 0), "FAIL": (0, 1, 0), "SKIP": (0, 0, 1)}[m.group(1)]),
+ ("go test -json", re.compile(r'^\{.*"Action":"(pass|fail|skip)".*"Test":"[^"]+"'), lambda m: {"pass": (1, 0, 0), "fail": (0, 1, 0), "skip": (0, 0, 1)}[m.group(1)]),
+ ("dotnet test", re.compile(r"^(?:Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+(\d+),\s+Skipped:\s+(\d+)"), lambda m: (int(m.group(2)), int(m.group(1)), int(m.group(3)))),
+ ("jest", re.compile(r"^\s*Tests:\s+(.*\b\d+ total)\s*$"), _jest),
+ ("vitest", re.compile(r"^\s*Tests\s{2,}(.*)\(\d+\)\s*$"), _jest),
+ ("ctest", re.compile(r"^\d+% tests passed, (\d+) tests? failed out of (\d+)"), _ctest),
+ ("phpunit", re.compile(r"^OK \((\d+) tests?, \d+ assertions?\)"), lambda m: (int(m.group(1)), 0, 0)),
+ ("phpunit", re.compile(r"^(Tests: \d+, Assertions: \d+.*?)\.?\s*$"), _php),
+)
+UNITTEST_RAN = re.compile(r"^Ran (\d+) tests? in [\d.]+s\s*$")
+UNITTEST_END = re.compile(r"^(?:OK|FAILED)(?: \(([^)]*)\))?\s*$")
+
+
+def parse_runner_log(text):
+ """(executed, failed, skipped, runners) from the runner's own summary lines, summed over the log; None when no line is recognised.
+ Recognised: Maven/Gradle, cargo, pytest, unittest, go test (-v or -json), dotnet test, jest, vitest, ctest, phpunit."""
+ passed = failed = skipped = 0
+ seen, ran = [], None
+ for line in text.split("\n")[:3000000]:
+ line = line.rstrip("\r")[:LOG_LINE]
+ if ran is not None and line.strip():
+ m = UNITTEST_END.match(line)
+ if m:
+ w = {k: int(v) for k, v in re.findall(r"(\w+)=(\d+)", (m.group(1) or "")[:LOG_LINE])}
+ f, sk = w.get("failures", 0) + w.get("errors", 0), w.get("skipped", 0)
+ passed, failed, skipped = passed + max(0, ran - f - sk), failed + f, skipped + sk
+ seen.append("unittest")
+ ran = None
+ m = UNITTEST_RAN.match(line)
+ if m:
+ ran = int(m.group(1))
+ continue
+ for name, rx, read in LOG_LINES:
+ m = rx.match(line)
+ if m:
+ p, f, sk = read(m)
+ passed, failed, skipped = passed + p, failed + f, skipped + sk
+ seen.append(name)
+ break
+ return (passed + failed, failed, skipped, sorted(set(seen))) if seen else None
+
+
+def read_logs(paths):
+ """Saved runner logs -> {"files", "executed", "failed", "skipped", "runners", "oldest", "newest", "unrecognised"}. A log without a summary line of a known runner is no evidence."""
+ out = {"files": 0, "executed": 0, "failed": 0, "skipped": 0, "runners": [], "oldest": None, "newest": None, "unrecognised": []}
+ for path in paths:
+ try:
+ st = os.lstat(path)
+ if not stat.S_ISREG(st.st_mode) or st.st_size > LOG_CAP:
+ out["unrecognised"].append("%s (a link, not a file, or larger than %d MB)" % (clean(os.path.basename(path), 80), LOG_CAP >> 20))
+ continue
+ with open(path, "rb") as fh:
+ got = parse_runner_log(fh.read(LOG_CAP).decode("utf-8", "replace"))
+ except OSError:
+ out["unrecognised"].append("%s (could not be read)" % clean(os.path.basename(path), 80))
+ continue
+ if got is None:
+ out["unrecognised"].append("%s (no summary line of a runner this script knows)" % clean(os.path.basename(path), 80))
+ continue
+ out["files"] += 1
+ out["executed"], out["failed"], out["skipped"] = out["executed"] + got[0], out["failed"] + got[1], out["skipped"] + got[2]
+ out["runners"] = sorted(set(out["runners"]) | set(got[3]))
+ out["oldest"] = st.st_mtime if out["oldest"] is None else min(out["oldest"], st.st_mtime)
+ out["newest"] = st.st_mtime if out["newest"] is None else max(out["newest"], st.st_mtime)
+ return out
+
+
+def utc(ts):
+ return datetime.datetime.fromtimestamp(ts or 0, datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
+
+
+def suite_evidence(suite, workspace):
+ """-> (counts for one suite, its parsed JUnit-style results or None). Evidence, best first: result files, a saved raw runner log,
+ and only then the counts the command typed, which are never enough for PROVEN."""
+ ev = {"name": suite["name"], "command": suite["command"], "date": suite["date"], "note": suite["note"], "notes": [], "source": "reported" if suite["executed"] is not None else "none",
+ "files": 0, "newest": None, "oldest": None, "written": "", "executed": suite["executed"] or 0, "failed": suite["failed"] or 0, "skipped": suite["skipped"] or 0,
+ "skippedNoReason": (suite["skipped"] or 0) if not suite["skippedReason"] else 0}
+ said = {"executed": suite["executed"], "failed": suite["failed"], "skipped": suite["skipped"]}
+ junit = [(j, inside(workspace, j)) for j in suite["junit"]]
+ logs = [(j, inside(workspace, j)) for j in suite["log"]]
+ ev["notes"] += ["%s is outside the workspace, so it was not read" % clean(j, 100) for j, p in junit + logs if p is None]
+
+ def mismatch(mine):
+ for label, value in mine.items():
+ if said[label] is not None and said[label] != value:
+ ev["notes"].append("the suite reported %d %s but the files show %d; the files were used" % (said[label], label, value))
+
+ good = [p for _, p in junit if p]
+ if good:
+ fresh = baseline_diff.read_results(good)
+ ev["notes"] += ["result file not used: " + u for u in fresh["unreadable"][:3]]
+ if fresh["files"]:
+ c = baseline_diff.tally(fresh["tests"].values())
+ ev.update({"source": "result files", "files": fresh["files"], "newest": fresh["newest"], "oldest": fresh["oldest"], "written": utc(fresh["newest"]), "executed": c["executed"],
+ "failed": c["fail"] + c["error"], "skipped": c["skip"],
+ "skippedNoReason": 0 if suite["skippedReason"] else sum(1 for t, st in fresh["tests"].items() if st == "SKIP" and not fresh["skipReasons"].get(t))})
+ mismatch({"executed": ev["executed"], "failed": ev["failed"], "skipped": ev["skipped"]})
+ return ev, fresh
+ ev["notes"].append("no readable result file was found under %s" % ", ".join(clean(j, 100) for j, p in junit if p))
+ good = [p for _, p in logs if p]
+ if good:
+ got = read_logs(good)
+ ev["notes"] += ["log not used: " + u for u in got["unrecognised"][:3]]
+ if got["files"]:
+ ev.update({"source": "runner log", "files": got["files"], "newest": got["newest"], "oldest": got["oldest"], "written": utc(got["newest"]), "executed": got["executed"],
+ "failed": got["failed"], "skipped": got["skipped"], "skippedNoReason": 0 if suite["skippedReason"] else got["skipped"]})
+ ev["notes"].append("counts read from the summary lines of %s" % ", ".join(got["runners"]))
+ mismatch({"executed": ev["executed"], "failed": ev["failed"], "skipped": ev["skipped"]})
+ return ev, None
+
+
+# ---------------------------------------------------------------- the source check
+SOURCE_CAP, EXAMPLES = 400000, 20
+NO_VCS = "by modification time, and no version-control tool was run"
+
+
+def reference_time(adir):
+ """When the analysis began: the modification time of PREFLIGHT.md, else that of the oldest file in analysis/<system>/."""
+ def mtime(path):
+ try:
+ st = os.lstat(path)
+ return st.st_mtime if stat.S_ISREG(st.st_mode) else None
+ except OSError:
+ return None
+ ref = mtime(os.path.join(adir, "PREFLIGHT.md"))
+ if ref is not None:
+ return ref
+ try:
+ times = [t for t in (mtime(os.path.join(adir, n)) for n in os.listdir(adir)) if t is not None]
+ except OSError:
+ return None
+ return min(times) if times else None
+
+
+def source_check(workspace, system, adir):
+ """-> {"state": clean|changed|unknown, "method", "detail", "files", "path", "target"} for legacy/<system>.
+ A plain file walk, never following a link and never running a program in the tree: any regular file newer than the
+ analysis is reported as changed. A walk that cannot finish is "not checked", never "untouched"."""
+ link = os.path.join(workspace, "legacy", system)
+ target = os.path.realpath(link) if os.path.lexists(link) else ""
+ out = {"state": "unknown", "method": NO_VCS, "detail": "", "files": [], "path": "legacy/" + system, "target": clean(target if os.path.islink(link) else "", 300)}
+ if not target or not os.path.isdir(target):
+ out["detail"] = "legacy/%s was not found, so it was not checked" % system
+ return out
+ ref = reference_time(adir)
+ if ref is None:
+ out["detail"] = "there is no PREFLIGHT.md or other analysis file to date the analysis by, so legacy/%s was not checked" % system
+ return out
+ newer, seen, unreadable = [], 0, [0]
+
+ def failed(_err):
+ unreadable[0] += 1
+
+ for base, dirs, names in os.walk(target, onerror=failed, followlinks=False):
+ dirs[:] = [d for d in dirs if d != ".git" and not os.path.islink(os.path.join(base, d))]
+ for n in names:
+ seen += 1
+ if seen > SOURCE_CAP:
+ break
+ full = os.path.join(base, n)
+ try:
+ st = os.lstat(full)
+ except OSError:
+ unreadable[0] += 1
+ continue
+ if stat.S_ISREG(st.st_mode) and st.st_mtime > ref:
+ newer.append(clean(os.path.relpath(full, target), 200))
+ if seen > SOURCE_CAP:
+ break
+ out["files"] = newer[:EXAMPLES]
+ if seen > SOURCE_CAP or unreadable[0]:
+ out["detail"] = "the walk could not finish (%s), so legacy/%s was not fully checked" % ("more than %d files" % SOURCE_CAP if seen > SOURCE_CAP else "%d path(s) could not be read" % unreadable[0], system)
+ out["state"] = "changed" if newer else "unknown"
+ if newer:
+ out["detail"] = "%d file(s) changed after the analysis started, and the walk could not finish" % len(newer)
+ return out
+ out["state"] = "changed" if newer else "clean"
+ out["detail"] = ("%d file(s) changed after the analysis started" % len(newer)) if newer else "no file changed after the analysis started (%d files compared)" % seen
+ return out
+
+
+# ---------------------------------------------------------------- the brief
+def brief_items(text, module, track):
+ """Unticked criteria a person decides: the exit criteria of the module's phase, and the open questions of section 7."""
+ if not text:
+ return {"found": False, "phase": "", "items": [], "count": 0}
+ lines = [ln[:2000] for ln in text.split("\n")]
+ phases, cur = [], None
+ for line in lines:
+ m = re.match(r"#{2,5}\s+Phase\s+(\d+)\b", line)
+ if m:
+ cur = {"n": int(m.group(1)), "title": clean(re.split(r"\s[—-]\s", line.lstrip("# "))[0], 60), "command": "", "modules": set(), "exit": [], "in_exit": False}
+ phases.append(cur)
+ elif re.match(r"#{1,3}\s", line):
+ cur = None
+ elif cur is not None:
+ k = re.match(r"\s*(Command|Modules)\s*:\s*(.*)$", line)
+ if k and k.group(1) == "Command":
+ cur["command"] = k.group(2).lower()
+ elif k:
+ cur["modules"] = {t.strip().lower() for t in re.split(r"[,;]", k.group(2)) if t.strip()}
+ elif re.match(r"\s*Exit criteria\s*:", line):
+ cur["in_exit"] = True
+ elif re.match(r"\s*(Entry criteria|Scale|Risk|Command|Modules)\s*:", line):
+ cur["in_exit"] = False
+ elif cur["in_exit"]:
+ c = CHECKBOX.match(line)
+ if c and c.group(1) == " ":
+ cur["exit"].append(clean(c.group(2), 300))
+ verb = {"rewrite": "transform", "reimagine": "reimagine", "uplift": "uplift"}[track]
+ by_name = [p for p in phases if module.lower() in p["modules"]] if track != "uplift" else []
+ mine = by_name or [p for p in phases if verb in p["command"]]
+ items = [{"text": t, "where": "%s exit criterion" % p["title"]} for p in mine for t in p["exit"]]
+ phase_n = min((p["n"] for p in mine), default=None)
+ level = None
+ for line in lines:
+ h = re.match(r"(#{1,3})\s+(.*)", line)
+ if h:
+ if re.match(r"(?:\d+[.)]?\s*)?open questions|7[.):\s]", h.group(2), re.I):
+ level = len(h.group(1))
+ elif level is not None and len(h.group(1)) <= level:
+ level = None
+ continue
+ c = CHECKBOX.match(line) if level else None
+ if c and c.group(1) == " ":
+ tag = re.search(r"\[before Phase (\d+)\]", c.group(2), re.I)
+ if not (tag and phase_n is not None and int(tag.group(1)) > phase_n):
+ items.append({"text": clean(c.group(2).replace("**", ""), 300), "where": "open question, section 7"})
+ return {"found": True, "phase": mine[0]["title"] if len(mine) == 1 else "", "items": items[:LIST_CAP], "count": len(items)}
+
+
+# ---------------------------------------------------------------- the six checks
+def row(cid, state, detail, **extra):
+ r = {"id": cid, "label": dict(CHECKS)[cid], "state": state, "detail": clean(detail, 700)}
+ r.update(extra)
+ return r
+
+
+def judge(path):
+ """A cases file judged again with compare.py: (record or None, problem)."""
+ if os.path.islink(path):
+ return None, "%s is a link, so it was not read" % clean(os.path.basename(path), 80)
+ try:
+ return compare.run(path, None, False), None
+ except compare.InputError as err:
+ return None, clean(str(err), 200)
+ except (OSError, ValueError, RecursionError, MemoryError) as err:
+ return None, "the cases file could not be judged (%s)" % err.__class__.__name__
+
+
+def mask_summary(records):
+ """Fields the comparison ignored, grouped by the reason given for them: [{"why", "cases"}]."""
+ groups = {}
+ for r in records:
+ for m in r["masked"]:
+ why = re.search(r"\(([^()]*)\)\s*$", m)
+ groups.setdefault(clean(why.group(1).strip() if why else "no reason given: " + m, 200), set()).add(r["id"])
+ return [{"why": k, "cases": len(v)} for k, v in sorted(groups.items())][:10]
+
+
+def tolerance_summary(records):
+ """The declared numeric tolerances that were used, grouped: [{"why", "rel", "abs", "cases"}]. A tolerance is never silent."""
+ groups = {}
+ for r in records:
+ if r.get("withinTolerance") and isinstance(r.get("tolerance"), dict):
+ t = r["tolerance"]
+ groups.setdefault((clean(t.get("why"), 200), t.get("rel"), t.get("abs")), set()).add(r["id"])
+ return [{"why": k[0], "rel": k[1], "abs": k[2], "cases": len(v)} for k, v in sorted(groups.items(), key=lambda kv: str(kv[0]))][:10]
+
+
+def summary_of(rec):
+ t = rec["totals"]
+ return {"cases": t["cases"], "executed": t["executed"], "same": t["same"], "differs": t["differs"], "missing": t["missing"], "selfCheck": rec["selfCheck"]["passed"],
+ "withinTolerance": t.get("sameWithinTolerance", 0), "tolerances": tolerance_summary(rec["cases"]),
+ "approved": [{"id": r["id"], "why": clean(r["approvedDifference"], 300)} for r in rec["cases"] if r["verdict"] == "differs-approved"][:LIST_CAP],
+ "masks": mask_summary(rec["cases"]),
+ "differing": [{"id": r["id"], "reason": clean(r["reason"], 300)} for r in rec["cases"] if r["verdict"] in ("differs", "missing")][:LIST_CAP]}
+
+
+def cases_paths(adir, module, n_subjects):
+ """The cases files of a module: its own folder equivalence/<module>/, else the shared equivalence/ folder."""
+ for base, shared in ((os.path.join(adir, "equivalence", module), False), (os.path.join(adir, "equivalence"), True)):
+ cases, fresh = os.path.join(base, "cases.json"), os.path.join(base, "fresh-cases.json")
+ if os.path.lexists(cases) or os.path.lexists(fresh):
+ return {"cases": cases if os.path.lexists(cases) else "", "fresh": fresh if os.path.lexists(fresh) else "", "shared": shared and n_subjects > 1}
+ return {"cases": "", "fresh": "", "shared": False}
+
+
+def recorded_matches(path, rec):
+ """Does EQUIVALENCE.json on disk agree with what the cases say now? None when there is no usable file."""
+ obj, _ = read_json(path)
+ if not isinstance(obj, dict) or not isinstance(obj.get("totals"), dict):
+ return None
+ mine = rec["totals"]
+ return all(obj["totals"].get(k) == mine[k] for k in ("cases", "executed", "same", "differs", "differsApproved", "missing"))
+
+
+def check_tests(g, uplift, comparable):
+ """Check 1. g: {executed, failed, skipped, skippedNoReason, suites, stale}. A suite's own note is added to the detail."""
+ r = check_tests_state(g, uplift, comparable)
+ notes = " ".join(e["note"] for e in g["suites"] if e.get("note"))
+ if notes:
+ r["detail"] = clean(r["detail"] + " Note: " + notes, 700)
+ return r
+
+
+def check_tests_state(g, uplift, comparable):
+ ex, fail, skip, nr = g["executed"], g["failed"], g["skipped"], g["skippedNoReason"]
+ if not g["suites"]:
+ return row("tests", "fail", "No test run is recorded for this module, so nothing executed. Run its tests again and record them in equivalence/test-runs.json.")
+ unread = [e["name"] or "a suite" for e in g["suites"] if e["source"] == "none"]
+ if len(unread) == len(g["suites"]):
+ return row("tests", "gap", "No test result could be read: no result file was parsed, no saved runner log has a summary line this script knows, and no counts were given (%s)." % "; ".join(n for e in g["suites"] for n in e["notes"][:2])[:300])
+ if ex == 0:
+ return row("tests", "fail", "Nothing executed: no test ran%s." % (" (%d were skipped)" % skip if skip else ""))
+ if fail and not (uplift and comparable):
+ return row("tests", "fail", "%d of %d executed test(s) failed." % (fail, ex))
+ if nr and not (uplift and comparable):
+ return row("tests", "gap", "%d test(s) were skipped with no reason given (%d executed, %d failed)." % (nr, ex, fail))
+ if g["stale"]:
+ return row("tests", "gap", "%d test(s) executed, but some result files are older than the code, so this was not a clean run of the current code: delete the build output and run the tests again." % ex)
+ typed = [e["name"] or "a suite" for e in g["suites"] if e["source"] == "reported"]
+ if unread or typed:
+ return row("tests", "gap", "%d test(s) executed, but the counts for %s were typed in by the command, not read from a result file or a saved runner log, so this cannot be PROVEN." % (ex, ", ".join(unread + typed)))
+ judged = " (failures are judged against the baseline below)" if fail and uplift else ""
+ return row("tests", "pass", "%d test(s) executed, %d failed%s, %d skipped." % (ex, fail, judged, skip))
+
+
+def check_rules(ctx, subject, evidence, caveats):
+ """Check 2."""
+ if subject["track"] == "uplift":
+ return row("rules", "na", "An uplift keeps the code, so no business rule is traced. The baseline comparison stands in.")
+ tr = ctx["trace"]
+ if tr is None:
+ return row("rules", "gap", ctx["trace_problem"])
+ if not tr["rules"]:
+ return row("rules", "gap", "BUSINESS_RULES.md has no rule cards in the form '### RULE-001: name', so no rule can be traced.")
+ view = trace_rules.module_view(tr, subject["rel"])
+ p0 = [r for r in view["rows"] if r["priority"] == "P0"]
+ missing = [r["id"] for r in p0 if r["status"] != "tested"]
+ evidence["rules"] = {"tied": view["tied"], "counted": len(view["rows"]), "outOfScope": view["outOfScope"], "totals": view["totals"], "p0NoTests": missing,
+ "p0": [{"id": r["id"], "name": r["name"], "confidence": r["confidence"], "status": r["status"], "main": r["main"], "tests": r["tests"], "claimed": r["claimed"],
+ "where": clean((r["samples"]["tests"] or r["samples"]["main"] or [""])[0], 200)} for r in p0][:100]}
+ if not view["tied"]:
+ caveats.append("Nothing ties a rule to this module by name, so every rule in BUSINESS_RULES.md was counted.")
+ if not p0:
+ return row("rules", "pass", "No rule this module answers for is rated P0 (%d rule(s) counted)." % len(view["rows"]))
+ if missing:
+ claimed = sum(1 for r in p0 if r["status"] == "claimed only")
+ return row("rules", "gap", "%d of %d P0 rule(s) are not named by any test: %s%s." % (len(missing), len(p0), ", ".join(missing[:12]), " (%d claimed only in the notes)" % claimed if claimed else ""))
+ return row("rules", "pass", "All %d P0 rule(s) this module answers for are named by at least one test." % len(p0))
+
+
+def baseline_state(ctx, suites, xml_paths, evidence, caveats, person):
+ """The uplift's baseline comparison: (state, detail, whether it could compare)."""
+ path = os.path.join(ctx["adir"], "BASELINE.md")
+ if not os.path.isfile(path):
+ return "gap", "BASELINE.md is missing: an uplift needs the old version's results recorded first (uplift, Step 4).", False
+ if not xml_paths:
+ return "gap", "BASELINE.md exists, but there are no result files to compare it with.", False
+ try:
+ b = baseline_diff.run(path, xml_paths)
+ except baseline_diff.InputError as err:
+ return "gap", clean(str(err), 300), False
+ keys = ("ok", "regressionsCount", "newFailuresCount", "fixedCount", "missingCount", "missingModulesCount", "moduleDiffsCount", "renamed", "executedDrop", "skippedGrowth",
+ "stillFailingCount", "newlySkippedCount", "flakyCount", "approvedCount")
+ evidence["baseline"] = dict({k: b[k] for k in keys}, source=b["baseline"]["source"], targetOnly=b["baseline"]["targetOnly"], why=b["baseline"]["why"], before=b["baseline"]["counts"],
+ now=b["fresh"]["counts"], approved=b["approved"][:LIST_CAP], regressions=b["regressions"][:LIST_CAP], newFailures=b["newFailures"][:LIST_CAP], fixed=b["fixed"][:LIST_CAP], missing=b["missing"][:LIST_CAP])
+ if b["fixedCount"]:
+ person.append("%d test(s) failed on the old version and pass now. A person decides whether each is an intended fix." % b["fixedCount"])
+ if b["flakyCount"]:
+ caveats.append("%d test(s) the baseline lists as flaky flipped; they are not counted as regressions." % b["flakyCount"])
+ if b["approvedCount"]:
+ caveats.append("%d test difference(s) were approved by a person in BASELINE.md and are not counted: %s." % (
+ b["approvedCount"], "; ".join("%s (%s)" % (clean(x["id"], 80), clean(x["reason"] or "no reason given", 80)) for x in b["approved"][:5])))
+ if b["baseline"]["targetOnly"] or not b["baseline"]["counts"]:
+ return "gap", "The baseline says target-only (%s): the old version did not run here, so there is nothing to compare with." % (b["baseline"]["why"] or "no reason given"), False
+ if b["renamed"]:
+ caveats.append("%d test name(s) changed while their class did not get worse (parameterized names that embed a path, for example); they were not counted as missing." % b["renamed"])
+ if b["regressionsCount"] or b["newFailuresCount"]:
+ hint = " Tests the baseline never listed were added after it was recorded: run them on the old version too and add them to BASELINE.md to tell a regression from a test that was never green." if b["newFailuresCount"] else ""
+ return "fail", "%d test(s) passed before and fail now; %d test(s) the baseline never listed (or skipped) fail now.%s" % (b["regressionsCount"], b["newFailuresCount"], hint), True
+ gaps = ["%d %s" % (n, what) for n, what in ((b["missingCount"], "baseline test(s) did not run now"), (b["missingModulesCount"], "baseline module(s) are missing from the results"),
+ (b["moduleDiffsCount"], "module(s) ran fewer tests or skipped more"), (b["newlySkippedCount"], "test(s) that passed before are skipped now")) if n]
+ if b["executedDrop"]:
+ gaps.append("executed tests dropped from %(before)d to %(now)d" % b["executedDrop"])
+ if gaps:
+ return "gap", "; ".join(gaps) + ".", True
+ return "pass", "No regression: %d test(s) executed against %d in the baseline (%s)." % (b["fresh"]["counts"]["executed"], b["baseline"]["counts"]["executed"], b["baseline"]["source"]), True
+
+
+def check_same(ctx, subject, paths, dev, dev_problem, base, evidence, caveats):
+ """Check 3. `base` is baseline_state's answer for an uplift, else None."""
+ uplift, dev_state, dev_detail = subject["track"] == "uplift", None, ""
+ if dev:
+ s = evidence["equivalence"] = summary_of(dev)
+ problem = compare.verdict_of(dev)
+ dev_state = "pass" if not problem else "fail"
+ dev_detail = "%d of %d development case(s) executed: %d same%s, %d differ, %d missing; comparator self-check %s." % (
+ s["executed"], s["cases"], s["same"], " (%d within a declared tolerance)" % s["withinTolerance"] if s["withinTolerance"] else "", s["differs"], s["missing"],
+ {True: "passed", False: "FAILED", None: "not applicable"}[s["selfCheck"]])
+ if problem and not (s["differs"] or s["missing"]):
+ dev_detail = "Not proven: %s." % clean(problem, 200)
+ if s["approved"]:
+ dev_detail += " %d difference(s) a person approved are listed." % len(s["approved"])
+ if recorded_matches(os.path.join(ctx["adir"], "EQUIVALENCE.json"), dev) is False:
+ caveats.append("EQUIVALENCE.json does not match a fresh comparison of the cases: run compare.py again so the report shows the current result.")
+ if paths["shared"]:
+ caveats.append("The equivalence cases are shared by every module, so they are not attributed to this module alone.")
+ elif dev_problem:
+ caveats.append(dev_problem)
+ if uplift:
+ b_state, b_detail, comparable = base
+ detail = " ".join(x for x in (b_detail, dev_detail) if x)
+ if "fail" in (dev_state, b_state):
+ return row("same", "fail", detail)
+ if comparable:
+ return row("same", b_state, detail)
+ return row("same", "pass" if dev_state == "pass" else "gap", detail)
+ if dev_state:
+ return row("same", dev_state, dev_detail)
+ if os.path.isfile(os.path.join(ctx["adir"], "EQUIVALENCE.json")):
+ return row("same", "gap", "EQUIVALENCE.json exists, but the cases behind it (equivalence/cases.json) were not found, so it could not be judged again.")
+ return row("same", "gap", "No equivalence cases were recorded: the new code was never compared with the legacy output.")
+
+
+def input_labels(path):
+ """{case id: input label} from the raw cases file. A case may carry "input": "F01" so that several output files of one
+ run count as one input; a case without a label counts as its own input."""
+ obj, _ = read_json(path)
+ cases = obj.get("cases") if isinstance(obj, dict) and isinstance(obj.get("cases"), list) else []
+ return {clean(c.get("id"), 80): clean(c.get("input"), 80) for c in cases[:100000] if isinstance(c, dict) and isinstance(c.get("input"), str) and c.get("input").strip()}
+
+
+def check_fresh(ctx, paths, dev, legacy_ran, frs, fr_problem, evidence):
+ """Check 4."""
+ legacy = ctx["runs"]["legacy"]
+ if ctx["runs"]["leftOut"]:
+ evidence["leftOut"] = ctx["runs"]["leftOut"]
+ if not legacy_ran:
+ return row("fresh", "gap", "The legacy could not run here%s, so the proof is trace-based: no fresh-input comparison was possible and the verdict cannot be PROVEN." % (" (%s)" % legacy["why"] if legacy["why"] else ""))
+ if frs is None:
+ return row("fresh", "gap", "The fresh-input check was not run: no equivalence/fresh-cases.json%s." % (" (%s)" % fr_problem if fr_problem else ""))
+ s = summary_of(frs)
+ dev_hashes = {r["legacySha256"] for r in dev["cases"] if r["legacySha256"]} if dev else set()
+ ran = ("same", "differs", "differs-approved")
+ reused = {r["id"] for r in frs["cases"] if r["verdict"] in ran and r["legacySha256"] in dev_hashes}
+ empty = {r["id"] for r in frs["cases"] if r["verdict"] in ran and r.get("empty")}
+ labels = input_labels(paths["fresh"])
+ counted = [r["id"] for r in frs["cases"] if r["verdict"] in ran and r["id"] not in reused and r["id"] not in empty]
+ inputs = len({labels.get(c) or c for c in counted})
+ s.update({"reused": sorted(reused)[:LIST_CAP], "comparisons": len(counted), "inputs": inputs, "needed": FRESH_MIN})
+ evidence["fresh"] = s
+ if ctx["runs"]["leftOut"]:
+ s["leftOut"] = ctx["runs"]["leftOut"]
+ if s["differs"] or s["missing"] or s["selfCheck"] is False:
+ shown = s["differing"][:5]
+ why = "; ".join("%s: %s" % (d["id"], d["reason"]) for d in shown) or "the comparator's self-check failed"
+ more = " ... and %d more (see VERIFICATION.json)" % (s["differs"] + s["missing"] - len(shown)) if s["differs"] + s["missing"] > len(shown) else ""
+ return row("fresh", "fail", "%d fresh comparison(s) differ and %d are missing (of %d): %s%s" % (s["differs"], s["missing"], s["cases"], why, more))
+ if inputs < FRESH_MIN:
+ return row("fresh", "gap", "Only %d new input(s) counted; at least %d are needed%s." % (inputs, FRESH_MIN, " (%d comparison(s) had the same legacy output as a development case, which is expected of status lines and does not count)" % len(reused) if reused else ""))
+ extra = ([" (%d approved by a person)" % len(s["approved"])] if s["approved"] else []) + ([" (%d within a declared tolerance)" % s["withinTolerance"]] if s["withinTolerance"] else [])
+ return row("fresh", "pass", "%d new input(s), %d comparison(s), ran on the legacy and the new code with no difference%s." % (inputs, len(counted), "".join(extra)))
+
+
+def canaries_in(text):
+ """Canary lines in a notes file: [(change, tests failed)]. Only lines that say Canary are looked at, each cut short."""
+ found = []
+ for line in [ln for ln in (text or "").split("\n") if "anary" in ln[:2000]][:500]:
+ for m in CANARY.finditer(line[:600]):
+ found.append((clean(m.group(1), 200), int(m.group(2).replace(",", ""))))
+ return found
+
+
+def canary_run(entry, workspace, clean_ids, clean_failed):
+ """Failures a canary run's own result file or saved runner log shows beyond the clean run's: (new failures or None, where).
+ With result files, a test that fails in both runs is not the canary's doing; with a log, only the count can be compared."""
+ junit, logs = [p for p in (inside(workspace, j) for j in entry["junit"]) if p], [p for p in (inside(workspace, j) for j in entry["log"]) if p]
+ if junit:
+ fresh = baseline_diff.read_results(junit)
+ if fresh["files"]:
+ bad = {t for t, st in fresh["tests"].items() if st in ("FAIL", "ERROR")}
+ return len(bad - clean_ids), [os.path.relpath(p, workspace).replace(os.sep, "/") for p in junit][:3]
+ if logs:
+ got = read_logs(logs)
+ if got["files"]:
+ return max(0, got["failed"] - clean_failed), [os.path.relpath(p, workspace).replace(os.sep, "/") for p in logs][:3]
+ return None, []
+
+
+def check_canary(subject, module, runs, evidence, workspace, others, clean_ids, clean_failed):
+ """Check 5. A canary counts only when its own result file or saved runner log, parsed here, shows tests that fail because of the break
+ (failures the clean run did not have). A line in the notes, or a count typed into test-runs.json, is a claim."""
+ shown, claimed = [], []
+ for c in runs["canaries"]:
+ mine = c["module"].lower() in ("", module.lower()) or (subject["track"] == "uplift" and c["module"].lower() not in others)
+ if not mine:
+ continue
+ failed, where = canary_run(c, workspace, clean_ids, clean_failed)
+ (shown if failed is not None else claimed).append({"change": c["change"], "testsFailed": failed if failed is not None else c["testsFailed"], "shown": failed is not None, "where": where})
+ for name in NOTE_NAMES:
+ claimed += [{"change": c, "testsFailed": n, "shown": False, "where": []} for c, n in canaries_in(read_text(os.path.join(subject["path"], name)))]
+ evidence["canary"] = (shown + claimed)[:10]
+ silent = [c for c in shown if c["testsFailed"] == 0]
+ if silent:
+ return row("canary", "fail", "A deliberate break was run and no test failed because of it: %s (%s)." % (silent[0]["change"] or "no description", ", ".join(silent[0]["where"])))
+ if shown:
+ first = shown[0]
+ return row("canary", "pass", "%d canary run(s) shown by a result file or log; the first (%s) made %d more test(s) fail than the clean run (%s).%s" % (
+ len(shown), first["change"] or "no description", first["testsFailed"], ", ".join(first["where"]), " %d more are only claimed." % len(claimed) if claimed else ""))
+ if claimed:
+ return row("canary", "gap", "A canary is claimed (%s) but no result file or saved runner log from that run is recorded, so it was not shown." % (claimed[0]["change"] or "no description"))
+ return row("canary", "gap", "No canary is recorded (a deliberate one-line break that makes tests fail), so the tests were never shown able to fail.")
+
+
+def check_source(ctx):
+ """Check 6."""
+ src, name = ctx["source"], "legacy/" + ctx["system"]
+ if src["state"] == "clean":
+ return row("source", "pass", "%s is untouched: %s. Checked %s." % (name, src["detail"], src["method"]))
+ if src["state"] == "changed":
+ return row("source", "gap", "%s has changed since the analysis began: %s. Checked %s.%s" % (name, src["detail"], src["method"], " First: %s." % ", ".join(src["files"][:3]) if src["files"] else ""))
+ return row("source", "gap", "%s: %s. Checked %s." % (name, src["detail"], src["method"]))
+
+
+def not_proven(subject, ev, legacy_ran):
+ """What even a PROVEN verdict would not tell you, specific to this module."""
+ out = ["It does not prove behavior on inputs nobody tried: the equivalence cases and the fresh inputs are samples, not the whole input space."]
+ if not legacy_ran:
+ out.append("The legacy could not run here, so the comparison rests on recorded outputs and traces. It is only as good as that recording.")
+ masks = (ev.get("equivalence") or {}).get("masks") or []
+ if masks:
+ out.append("Fields the comparison ignored could hide a difference there: %s." % "; ".join(m["why"] for m in masks[:5]))
+ for where, key in (("development cases", "equivalence"), ("fresh inputs", "fresh")):
+ for t in (ev.get(key) or {}).get("tolerances") or []:
+ out.append("Numbers may differ in the %s within a declared tolerance (relative %g, absolute %g) in %d case(s): %s. That is a person's rule, not an exact match." % (
+ where, t["rel"] or 0, t["abs"] or 0, t["cases"], t["why"]))
+ if (ev.get("equivalence") or {}).get("approved") or (ev.get("fresh") or {}).get("approved") or (ev.get("baseline") or {}).get("approvedCount"):
+ out.append("A difference a person approved is a decision, not evidence.")
+ out.append("It does not cover speed, capacity, security, concurrency, or anything the tests and cases do not exercise.")
+ if subject["track"] != "uplift":
+ out.append("It traces only the rules that were extracted: behavior nobody wrote down as a rule has no rule to trace.")
+ out.append("A test that names a rule shows the rule is mentioned, not that the test is a good one. The canary shows only that some test can fail.")
+ out.append("It does not replace the review and sign-off of the people who own the system.")
+ return out
+
+
+def evaluate(subject, ctx):
+ """-> the module record: verdict, reasons, the six checks and the evidence behind each."""
+ ws, module, uplift = ctx["workspace"], subject["name"], subject["track"] == "uplift"
+ suites = suites_for(ctx["runs"], subject, ctx["unit"], ctx["subjects"])
+ evidence, caveats, person = {}, [], []
+ per, xml_paths, oldest, clean_ids = [], [], None, set()
+ for s in suites:
+ ev, fresh = suite_evidence(s, ws)
+ per.append(ev)
+ caveats += ["%s: %s" % (ev["name"] or "a suite", n) for n in ev["notes"]]
+ if ev["oldest"] is not None:
+ oldest = ev["oldest"] if oldest is None else min(oldest, ev["oldest"])
+ if fresh:
+ xml_paths += [p for p in (inside(ws, j) for j in s["junit"]) if p]
+ clean_ids |= {t for t, st in fresh["tests"].items() if st in ("FAIL", "ERROR")}
+ g = {k: sum(e[k] for e in per) for k in ("executed", "failed", "skipped", "skippedNoReason")}
+ g.update({"suites": per, "stale": oldest is not None and code_mtime(subject["path"]) > oldest + 2}) # any result file older than the code: not a clean run
+ evidence["tests"] = dict({k: g[k] for k in ("executed", "failed", "skipped", "skippedNoReason", "stale")},
+ suites=[{k: e.get(k, "") for k in ("name", "command", "date", "note", "source", "files", "written", "executed", "failed", "skipped")} for e in per][:20])
+ base = baseline_state(ctx, suites, xml_paths, evidence, caveats, person) if uplift else None
+ paths = cases_paths(ctx["adir"], module, len(ctx["subjects"]))
+ dev, dev_problem = judge(paths["cases"]) if paths["cases"] else (None, None)
+ frs, fr_problem = judge(paths["fresh"]) if paths["fresh"] else (None, None)
+ legacy_ran = ctx["runs"]["legacy"]["ran"]
+ if uplift and evidence.get("baseline", {}).get("targetOnly"):
+ legacy_ran = False
+ if legacy_ran is None:
+ legacy_ran = bool(frs and frs["totals"]["executed"])
+ evidence["legacy"] = dict(ctx["runs"]["legacy"], ran=legacy_ran)
+ checks = [check_tests(g, uplift, bool(base and base[2])), check_rules(ctx, subject, evidence, caveats), check_same(ctx, subject, paths, dev, dev_problem, base, evidence, caveats),
+ check_fresh(ctx, paths, dev, legacy_ran, frs, fr_problem, evidence), check_canary(subject, module, ctx["runs"], evidence, ws, {x["name"].lower() for x in ctx["subjects"] if x["track"] != "uplift"}, clean_ids, g["failed"]), check_source(ctx)]
+ states = [c["state"] for c in checks]
+ label = dict(CHECKS)
+ return {"name": module, "track": subject["track"], "path": subject["rel"], "verdict": "NOT PROVEN" if "fail" in states else "PARTLY PROVEN" if "gap" in states else "PROVEN",
+ "reasons": ["%s: %s" % (label[c["id"]], c["detail"]) for c in checks if c["state"] in ("fail", "gap")],
+ "passed": ["%s: %s" % (label[c["id"]], c["detail"]) for c in checks if c["state"] == "pass"],
+ "checks": checks, "evidence": evidence, "caveats": caveats[:20], "needsPerson": person[:10], "brief": ctx["brief"](module, subject["track"]),
+ "notProven": not_proven(subject, evidence, legacy_ran), "verifiedAt": ctx["now"]}
+
+
+# ---------------------------------------------------------------- putting the pack together
+def build(system, workspace, module=None, now=None):
+ """-> the pack (a dict). Raises InputError when nothing is built to verify."""
+ workspace = os.path.abspath(workspace)
+ adir = os.path.join(workspace, "analysis", system)
+ now = now or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
+ everything = trace_rules.discover_modules(workspace, system)
+ if not everything:
+ raise InputError("nothing is built under modernized/ for %s: run transform, uplift or reimagine first" % system)
+ unit = None
+ if module and not any(m["name"].lower() == module.lower() for m in everything):
+ # not a module: it may be a unit inside an uplifted working copy, which narrows that copy's suites
+ if not any(m["track"] == "uplift" and os.path.isdir(os.path.join(m["path"], module)) and not os.path.islink(os.path.join(m["path"], module)) for m in everything):
+ raise InputError("nothing is built under modernized/ for %s module %s (built: %s)" % (system, module, ", ".join(clean(m["name"], 40) for m in everything[:10])))
+ unit = module
+ found = everything
+ runs = load_test_runs(adir)
+ try:
+ tr, tr_problem = trace_rules.trace(workspace, system), ""
+ except OSError as err:
+ tr, tr_problem = None, "%s, so no rule can be traced (run /code-modernization:modernize-extract-rules %s)." % (clean(str(err), 200), system)
+ brief = read_text(os.path.join(adir, "MODERNIZATION_BRIEF.md"))
+ ctx = {"workspace": workspace, "adir": adir, "system": system, "runs": runs, "subjects": everything, "unit": unit, "trace": tr, "trace_problem": tr_problem, "now": now,
+ "source": source_check(workspace, system, adir), "brief": lambda mod, track: brief_items(brief, mod, track)}
+ mods = [evaluate(s, ctx) for s in sorted(found, key=lambda s: s["name"].lower())]
+ problems = [clean(p, 300) for p in runs["problems"]] + ([] if runs["present"] else ["equivalence/test-runs.json was not found, so no test run is recorded and no module can be proven."])
+ return {"v": 1, "system": clean(system, 100), "generated": now, "asked": clean(module or "", 100), "rules": list(RULES_TEXT), "legacy": dict(ctx["source"], ran=runs["legacy"]["ran"]),
+ "problems": problems, "modules": mods, "signoff": {"name": "", "role": "", "date": "", "decision": ""}}
+
+
+def overall(pack):
+ counts = {v: sum(1 for m in pack["modules"] if m["verdict"] == v) for v in VERDICTS}
+ pack["overall"] = {"verdict": "NOT PROVEN" if counts["NOT PROVEN"] or not pack["modules"] else "PARTLY PROVEN" if counts["PARTLY PROVEN"] else "PROVEN", "counts": counts}
+ return pack
+
+
+# ---------------------------------------------------------------- VERIFICATION.md
+def cell(text):
+ return clean(text, 400).replace("|", "\\|")
+
+
+def render_md(pack):
+ o = pack["overall"]
+ out = ["# Verification: %s" % pack["system"], "",
+ "Written by `scripts/proof_pack.py` on %s. Each module's verdict is computed from the evidence files by the fixed rules at the end of this page. No model's opinion is part of it." % pack["generated"], "",
+ "**Overall: %s** (%s)" % (o["verdict"], ", ".join("%d %s" % (o["counts"][v], v.lower()) for v in VERDICTS if o["counts"][v]) or "no module"), ""]
+ out += ["- " + p for p in pack["problems"]]
+ if pack.get("asked"):
+ out += ["", "You asked about `%s`. Every built module is judged from its current evidence files on every run, so no verdict here depends on an earlier run." % cell(pack["asked"])]
+ src = pack["legacy"]
+ out += ["", "Legacy source: `%s`%s. Could it run here: %s. The source was checked %s." % (src["path"], " (a link to `%s`)" % src["target"] if src["target"] else "", {True: "yes", False: "no", None: "not stated"}[src.get("ran")], src["method"]), "",
+ "| Module | Track | Verdict | Tests executed | Failed | P0 rules tested | Same behavior | Fresh inputs |", "|---|---|---|---|---|---|---|---|"]
+ for m in pack["modules"]:
+ ev, st = m["evidence"], {c["id"]: c["state"] for c in m["checks"]}
+ p0 = ev.get("rules", {}).get("p0", [])
+ tested = "%d of %d" % (sum(1 for r in p0 if r["status"] == "tested"), len(p0)) if "rules" in ev else "not applicable"
+ out.append("| %s | %s | **%s** | %d | %d | %s | %s | %s |" % (cell(m["name"]), m["track"], m["verdict"], ev["tests"]["executed"], ev["tests"]["failed"], tested, WORDS[st["same"]], WORDS[st["fresh"]]))
+ for m in pack["modules"]:
+ ev, t, br = m["evidence"], m["evidence"]["tests"], m["brief"]
+ out += ["", "## %s: %s" % (cell(m["name"]), m["verdict"]), "", "Track: %s. Folder: `%s`. Checked %s." % (m["track"], cell(m["path"]), m["verifiedAt"]), ""]
+ if m["reasons"]:
+ out += ["**What is missing or wrong**", ""] + ["- " + cell(r) for r in m["reasons"]] + [""]
+ if m["passed"]:
+ out += ["**What passed**", ""] + ["- " + cell(r) for r in m["passed"]] + [""]
+ out += ["| Check | Result | Detail |", "|---|---|---|"]
+ out += ["| %s | %s | %s |" % (c["label"], WORDS[c["state"]], cell(c["detail"])) for c in m["checks"]]
+ out += ["", "tests executed: %d, failed %d, skipped %d" % (t["executed"], t["failed"], t["skipped"]), ""]
+ out += ["- %s: `%s` (from %s): %d executed, %d failed, %d skipped%s%s" % (cell(s["name"] or "suite"), cell(s["command"]), s["source"], s["executed"], s["failed"], s["skipped"],
+ ", %d result files written %s" % (s["files"], s["written"]) if s["files"] else "",
+ ". Note: " + cell(s["note"]) if s.get("note") else "") for s in t["suites"]]
+ if ev.get("rules", {}).get("p0"):
+ out += ["", "### P0 business rules", "", "| Rule | Name | Confidence | Result | Tests | Code | A test that names it |", "|---|---|---|---|---|---|---|"]
+ out += ["| %s | %s | %s | %s | %d | %d | %s |" % (r["id"], cell(r["name"]), r["confidence"] or "?", r["status"], r["tests"], r["main"], "`%s`" % cell(r["where"]) if r["where"] and r["tests"] else "") for r in ev["rules"]["p0"]]
+ if "equivalence" in ev:
+ e = ev["equivalence"]
+ out += ["", "### Development cases, judged again", "", "%d of %d executed: %d same%s, %d differ, %d missing." % (
+ e["executed"], e["cases"], e["same"], " (%d within a declared tolerance)" % e["withinTolerance"] if e["withinTolerance"] else "", e["differs"], e["missing"])]
+ out += ["- Declared tolerance (relative %g, absolute %g), %d case(s): %s" % (t["rel"] or 0, t["abs"] or 0, t["cases"], cell(t["why"])) for t in e["tolerances"]]
+ out += ["- Approved difference %s: %s" % (cell(a["id"]), cell(a["why"])) for a in e["approved"]] + ["- Ignored by the comparison: %s (%d case(s))" % (cell(x["why"]), x["cases"]) for x in e["masks"]]
+ out += ["- %s: %s" % (cell(d["id"]), cell(d["reason"])) for d in e["differing"]]
+ if "baseline" in ev:
+ b = ev["baseline"]
+ out += ["", "### Baseline comparison", "", "%d regression(s), %d new failure(s), %d fixed, %d missing, %d renamed." % (b["regressionsCount"], b["newFailuresCount"], b["fixedCount"], b["missingCount"], b["renamed"])]
+ out += ["- Regression: %s (%s, now %s)" % (cell(x["id"]), x["before"], x["now"]) for x in b["regressions"][:10]] + ["- New failure: " + cell(x) for x in b["newFailures"][:10]]
+ if ev.get("baseline", {}).get("approvedCount"):
+ out += ["- Difference a person approved in BASELINE.md: %s (%s)" % (cell(x["id"]), cell(x["reason"] or "no reason given")) for x in ev["baseline"]["approved"][:10]]
+ if ev.get("leftOut"):
+ out += ["", "Inputs left out of the fresh check: " + "; ".join(cell(x) for x in ev["leftOut"])]
+ if "fresh" in ev:
+ f = ev["fresh"]
+ out += ["", "### Fresh inputs", "", "%d new input(s) counted from %d comparison(s) executed: %d same%s, %d differ, %d missing." % (
+ f["inputs"], f["executed"], f["same"], " (%d within a declared tolerance)" % f["withinTolerance"] if f["withinTolerance"] else "", f["differs"], f["missing"])]
+ out += ["- Declared tolerance (relative %g, absolute %g), %d case(s): %s" % (t["rel"] or 0, t["abs"] or 0, t["cases"], cell(t["why"])) for t in f["tolerances"]]
+ out += ["- Not counted, because the legacy output equals a development output (status lines repeat by nature): " + ", ".join(cell(x) for x in f["reused"][:20])] if f["reused"] else []
+ out += (["", "### Caveats", ""] + ["- " + cell(c) for c in m["caveats"]]) if m["caveats"] else []
+ out += ["", "### Waiting for a person", "", "Claude never ticks these. A person decides them.", ""]
+ out += ["- [ ] %s [%s]" % (cell(i["text"]), i["where"]) for i in br["items"]] + ["- [ ] " + cell(n) for n in m["needsPerson"]]
+ if not br["items"] and not m["needsPerson"]:
+ out.append("- The brief lists no unticked criterion for this module." if br["found"] else "- No MODERNIZATION_BRIEF.md was found, so no criterion could be listed.")
+ if br["count"] > len(br["items"]):
+ out.append("- ... and %d more in the brief." % (br["count"] - len(br["items"])))
+ out += ["", "### What this does not prove", ""] + ["- " + cell(n) for n in m["notProven"]]
+ s = pack["signoff"]
+ out += ["", "## Sign-off", "", "A person fills this in. Claude leaves it blank.", "", "| | |", "|---|---|", "| Name | %s |" % (s["name"] or "________________"), "| Role | %s |" % (s["role"] or "________________"),
+ "| Date | %s |" % (s["date"] or "__________"), "| Decision | %s |" % (s["decision"] or "accept / accept with conditions / reject"), "", "## How each verdict is computed", ""]
+ return "\n".join(out + [pack["rules"][0], ""] + pack["rules"][1:]) + "\n"
+
+
+def write_outputs(pack, adir):
+ for name, text in (("VERIFICATION.json", json.dumps(pack, indent=2, ensure_ascii=True) + "\n"), ("VERIFICATION.md", render_md(pack))):
+ try:
+ compare.write_atomic(os.path.join(adir, name), text)
+ except compare.InputError as err:
+ raise InputError(str(err))
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description="Compute a verdict per built module from the evidence files and write VERIFICATION.md and VERIFICATION.json.")
+ ap.add_argument("system", help="the system's folder name under analysis/")
+ ap.add_argument("module", nargs="?", help="the module you re-tested (or a unit of an uplifted copy); every built module is judged from its current evidence either way")
+ ap.add_argument("--workspace", default=".", help="the project root holding analysis/ and modernized/ (default: current folder)")
+ args = ap.parse_args(argv)
+ for name in (args.system, args.module or "x"):
+ if not name or name in (".", "..") or re.search(r"[\\/\x00]", name):
+ print("proof_pack.py: the system and module must be folder names, not paths", file=sys.stderr)
+ return 2
+ adir = os.path.join(os.path.abspath(args.workspace), "analysis", args.system)
+ try:
+ pack = overall(build(args.system, args.workspace, args.module))
+ os.makedirs(adir, exist_ok=True)
+ write_outputs(pack, adir)
+ except InputError as err:
+ print("proof_pack.py: %s" % err, file=sys.stderr)
+ return 2
+ print("%s: %s" % (pack["system"], pack["overall"]["verdict"]))
+ for m in pack["modules"]:
+ print(" %s (%s): %s, tests executed: %d, failed %d" % (clean(m["name"], 60), m["track"], m["verdict"], m["evidence"]["tests"]["executed"], m["evidence"]["tests"]["failed"]))
+ for r in m["reasons"]:
+ print(" - " + clean(r, 300))
+ print("wrote analysis/%s/VERIFICATION.md and VERIFICATION.json" % args.system)
+ return 0 if pack["overall"]["verdict"] == "PROVEN" else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/code-modernization/scripts/tests/test_proof_tools.py b/plugins/code-modernization/scripts/tests/test_proof_tools.py
new file mode 100644
index 00000000..29e38997
--- /dev/null
+++ b/plugins/code-modernization/scripts/tests/test_proof_tools.py
@@ -0,0 +1,1368 @@
+"""Tests for scripts/trace_rules.py, baseline_diff.py, proof_pack.py and the Proof section of the report.
+
+Run: python3 -m unittest discover -s plugins/code-modernization/scripts/tests
+Every input here stands in for untrusted text from a legacy code base, so the hostile cases matter as much as the good ones.
+"""
+import contextlib
+import io
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+PLUGIN = os.path.dirname(os.path.dirname(HERE))
+sys.path.insert(0, os.path.join(PLUGIN, "scripts"))
+import baseline_diff as bd # noqa: E402
+import build_report as br # noqa: E402
+import compare as cmp # noqa: E402
+import proof_pack as pp # noqa: E402
+import trace_rules as tr # noqa: E402
+
+TEMPLATE = os.path.join(PLUGIN, "assets", "report-template.html")
+NODE = shutil.which("node")
+T0 = 1_700_000_000
+
+
+def put(root, rel, data, when=None):
+ path = os.path.join(root, *rel.split("/"))
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "wb") as fh:
+ fh.write(data if isinstance(data, bytes) else data.encode("utf-8"))
+ if when is not None:
+ os.utime(path, (when, when))
+ return path
+
+
+def run_main(fn, argv):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = fn(argv)
+ return code, out.getvalue(), err.getvalue()
+
+
+def read(path):
+ with open(path, encoding="utf-8") as fh:
+ return fh.read()
+
+
+def load(path):
+ return json.loads(read(path))
+
+
+def dump(path, obj):
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(obj, fh)
+
+
+def make_symlink(test, target, link):
+ try:
+ os.symlink(target, link)
+ except (OSError, NotImplementedError, AttributeError):
+ test.skipTest("symbolic links are not available here")
+
+
+def junit(cases, suite="S"):
+ """JUnit XML text from (classname, name, status, message) tuples; status is PASS, FAIL, ERROR or SKIP."""
+ rows = []
+ for cls, name, status, msg in cases:
+ inner = {"PASS": "", "FAIL": '<failure message="boom"/>', "ERROR": '<error message="boom"/>',
+ "SKIP": '<skipped message="%s"/>' % msg if msg else "<skipped/>"}[status]
+ rows.append('<testcase classname="%s" name="%s">%s</testcase>' % (cls, name, inner))
+ return '<?xml version="1.0"?><testsuite name="%s" tests="%d">%s</testsuite>' % (suite, len(rows), "".join(rows))
+
+
+def passing(n, cls="CalcTest"):
+ return [(cls, "case%d" % i, "PASS", "") for i in range(n)]
+
+
+# ---------------------------------------------------------------- trace_rules
+RULES_MD = """# Business Rules
+| ID | Name | Priority | Source |
+|---|---|---|---|
+| RULE-001 | Total | P0 | `app/mod.cbl:1-2` |
+
+### RULE-001: Interest total
+**Priority:** P0
+**Confidence:** High
+**Source:** `app/mod.cbl:1-2`
+
+### RULE-002: Rounding
+**Priority:** P0
+**Confidence:** Medium
+**Source:** `app/mod.cbl:3-9`
+
+### RULE-003: Date format
+**Priority:** P1
+**Confidence:** High
+**Source:** `app/other.cbl:3-9`
+
+### RULE-004: Old fee
+**Priority:** P2
+**Confidence:** Low
+**Source:** `app/other.cbl:30-39`
+"""
+
+
+class TraceRules(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root, True)
+ put(self.root, "analysis/s/BUSINESS_RULES.md", RULES_MD)
+
+ def status(self, result=None):
+ result = result or tr.trace(self.root, "s")
+ return {r["id"]: r["status"] for r in result["rules"]}
+
+ def test_tested_code_only_claimed_only_and_none(self):
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 pinned here\nvoid rule002_rounds() {}\n")
+ put(self.root, "modernized/s/mod/src/main/Calc.java", "// RULE-003: date\nclass Calc {}\n")
+ put(self.root, "modernized/s/mod/src/main/Fee.java", "class Fee {}\n")
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md",
+ "## Mapping\n\n| Behavior (rule) | Legacy | Target |\n|---|---|---|\n| Fee (RULE-004) | 30-39 | `src/main/Fee.java:1-5` |\n")
+ self.assertEqual(self.status(), {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "code only", "RULE-004": "claimed only"})
+
+ def test_a_claim_needs_a_file_that_exists_and_notes_are_never_tests(self):
+ put(self.root, "modernized/s/mod/src/main/Real.java", "class Real {}\n")
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md",
+ "| Behavior | Legacy | Target |\n|---|---|---|\n| One (RULE-001) | 1 | `src/main/Missing.java` |\n| Two (RULE-002, -003) | 2 | `src/main/Real.java:1` |\n")
+ put(self.root, "modernized/s/mod/README.md", "RULE-004 is covered by everything\n")
+ put(self.root, "modernized/s/mod/src/test/notes.txt", "RULE-004\n")
+ self.assertEqual(self.status(), {"RULE-001": "none", "RULE-002": "claimed only", "RULE-003": "claimed only", "RULE-004": "none"})
+
+ def test_a_table_under_a_not_migrated_heading_claims_nothing_and_a_test_beats_a_claim(self):
+ put(self.root, "modernized/s/mod/src/main/A.java", "class A {}\n")
+ put(self.root, "modernized/s/mod/src/test/ATest.java", "// RULE-002\n")
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md",
+ "## Not migrated\n\n| What | Why |\n|---|---|\n| Old fee RULE-004 | `src/main/A.java` dead code |\n\n## Mapping\n\n| Rule | Target |\n|---|---|\n| RULE-002 | `src/main/A.java` |\n")
+ self.assertEqual(self.status()["RULE-004"], "none")
+ self.assertEqual(self.status()["RULE-002"], "tested")
+
+ def test_only_exact_ids_count_and_neighbours_do_not(self):
+ put(self.root, "modernized/s/mod/src/test/T.java", "RULE-0010 RULE-1001 XRULE-001 rulebook-2 the rule of thumb, schedule_2, ruler-3\n")
+ self.assertEqual(set(self.status().values()), {"none"})
+ put(self.root, "modernized/s/mod/src/test/U.java", "// RULE_002 and testRule001 and rule-003\n")
+ self.assertEqual({k: v for k, v in self.status().items() if v == "tested"}, {"RULE-001": "tested", "RULE-002": "tested", "RULE-003": "tested"})
+
+ def test_what_counts_as_a_test_file(self):
+ for rel, kind in (("src/test/java/A.java", "test"), ("tests/x.py", "test"), ("web/__tests__/a.js", "test"), ("spec/a.rb", "test"), ("src/FooTest.java", "test"),
+ ("src/FooTests.cs", "test"), ("pkg/test_foo.py", "test"), ("pkg/foo_test.go", "test"), ("web/a.spec.ts", "test"), ("web/a.test.js", "test"),
+ ("src/main/Calc.java", "main"), ("src/Contest.java", "main"), ("src/latest.py", "main"), ("README.md", "doc"), ("notes/x.txt", "doc")):
+ self.assertEqual(tr.file_kind(rel), kind, rel)
+
+ def test_build_output_is_skipped(self):
+ for d in ("target", "build", "dist", "node_modules", "bin", "obj", "__pycache__", ".venv", ".git"):
+ put(self.root, "modernized/s/mod/%s/src/test/T.java" % d, "// RULE-001 RULE-002\n")
+ put(self.root, "modernized/s/mod/src/main/A.java", "class A {}\n")
+ self.assertEqual(set(self.status().values()), {"none"})
+
+ def test_p0_without_a_test_is_the_important_list_and_sets_the_exit_code(self):
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n")
+ result = tr.trace(self.root, "s")
+ self.assertEqual(result["p0NoTests"], ["RULE-002"])
+ self.assertEqual(result["totals"]["P0"], {"rules": 2, "tested": 1, "code only": 0, "claimed only": 0, "none": 1})
+ code, out, _ = run_main(tr.main, ["s", "--workspace", self.root])
+ self.assertEqual(code, 1)
+ self.assertIn("P0 rules with no test that names them: RULE-002", out)
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n")
+ self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root])[0], 0)
+
+ def test_module_view_counts_only_the_modules_rules_and_falls_back_to_all(self):
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n")
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "Legacy: `legacy/s/app/mod.cbl`\n")
+ put(self.root, "modernized/s/other/src/main/X.java", "class X {}\n")
+ result = tr.trace(self.root, "s")
+ view = tr.module_view(result, "modernized/s/mod")
+ self.assertTrue(view["tied"])
+ self.assertEqual([r["id"] for r in view["rows"]], ["RULE-001", "RULE-002"]) # both come from mod.cbl, which the notes name
+ nothing = tr.module_view(result, "modernized/s/other")
+ self.assertFalse(nothing["tied"])
+ self.assertEqual(len(nothing["rows"]), 4)
+ self.assertEqual(nothing["p0NoTests"], ["RULE-001", "RULE-002"]) # this module's own tests name neither
+
+ def test_all_option_lists_every_rule(self):
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n")
+ _, short, _ = run_main(tr.main, ["s", "--workspace", self.root])
+ _, everything, _ = run_main(tr.main, ["s", "--workspace", self.root, "--all"])
+ self.assertIn("RULE-004", everything)
+ self.assertEqual(len(re.findall(r"^RULE-\d+", everything, re.M)), 4)
+ self.assertLessEqual(len(short), len(everything))
+
+ def test_module_option_and_exit_codes(self):
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001 RULE-002\n")
+ code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--module", "MOD"])
+ self.assertEqual(code, 0)
+ self.assertIn("module mod", out)
+ self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root, "--module", "nope"])[0], 2)
+ for bad in ("..", "a/b", ""):
+ self.assertEqual(run_main(tr.main, [bad, "--workspace", self.root])[0], 2)
+ self.assertEqual(run_main(tr.main, ["missing", "--workspace", self.root])[0], 2)
+ code, out, _ = run_main(tr.main, ["s", "--workspace", self.root, "--json"])
+ self.assertEqual(json.loads(out)["system"], "s")
+
+ def test_hostile_files_are_read_as_text_and_never_followed_or_trusted(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "secret.java", "// RULE-001 RULE-002\n")
+ put(outside, "dir/T.java", "// RULE-001\n")
+ make_symlink(self, os.path.join(outside, "secret.java"), os.path.join(self.root, "modernized", "s", "mod", "src", "test", "LinkTest.java")) \
+ if os.makedirs(os.path.join(self.root, "modernized", "s", "mod", "src", "test")) is None else None
+ make_symlink(self, os.path.join(outside, "dir"), os.path.join(self.root, "modernized", "s", "mod", "src", "test", "linked"))
+ make_symlink(self, outside, os.path.join(self.root, "modernized", "s", "linkedmod"))
+ put(self.root, "modernized/s/mod/src/test/Huge.java", "RULE-001 " * 400000 + "x" * 3000000)
+ put(self.root, "modernized/s/mod/src/test/Line.java", "A-" * 2000000 + "\n" + "RULE-" * 300000 + "\n")
+ put(self.root, "modernized/s/mod/src/test/Binary.java", b"\x00\x01\x02 RULE-002 \x00")
+ put(self.root, "modernized/s/mod/src/test/Path.java", "// ../../RULE-002/../../etc/passwd and RULE-001/..\n")
+ started = time.time()
+ result = tr.trace(self.root, "s")
+ self.assertLess(time.time() - started, 20)
+ st = self.status(result)
+ self.assertEqual(st["RULE-001"], "tested") # by Path.java, which only names the id
+ self.assertEqual(st["RULE-002"], "tested") # "../../RULE-002/.." is a mention, and nothing was opened for it
+ self.assertEqual(result["scan"]["linksSkipped"], 2)
+ self.assertEqual([m["name"] for m in result["modules"]], ["mod"]) # the linked module folder is not a module
+ self.assertNotIn("secret.java", json.dumps(result))
+ os.remove(os.path.join(self.root, "modernized", "s", "mod", "src", "test", "Path.java"))
+ self.assertEqual(self.status()["RULE-002"], "none") # a NUL byte marks a file binary, and the links reached nothing
+
+ def test_a_link_in_place_of_the_rules_file_is_refused(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "R.md", RULES_MD)
+ os.remove(os.path.join(self.root, "analysis", "s", "BUSINESS_RULES.md"))
+ make_symlink(self, os.path.join(outside, "R.md"), os.path.join(self.root, "analysis", "s", "BUSINESS_RULES.md"))
+ code, _, err = run_main(tr.main, ["s", "--workspace", self.root])
+ self.assertEqual(code, 2)
+ self.assertIn("symbolic link", err)
+
+ def test_malformed_rules_files_do_not_crash(self):
+ for text in ("", "```\n### RULE-001: in a fence\n```\n", "### RULE-001: x\n### RULE-001: again\n**Priority:** P0\n",
+ "### RULE-001: \x1b[31mred\x1b[0m name\n**Priority:** " + "P0" * 100000 + "\n", "|" * 100000 + "\n" + "#" * 100000,
+ "### RULE-99999999999: too long\n", "\ufeff### RULE-007: bom\n**Priority:** P1\n"):
+ put(self.root, "analysis/s/BUSINESS_RULES.md", text)
+ result = tr.trace(self.root, "s")
+ for r in result["rules"]:
+ self.assertNotRegex(r["name"] + r["source"], r"[\x00-\x1f\x7f]")
+ put(self.root, "analysis/s/BUSINESS_RULES.md", "### RULE-001: x\n### RULE-001: again\n")
+ result = tr.trace(self.root, "s")
+ self.assertEqual(len(result["rules"]), 1)
+ self.assertTrue(any("more than one card" in n for n in result["notes"]))
+ put(self.root, "analysis/s/BUSINESS_RULES.md", b"### RULE-001: x\x00\n") # a NUL byte makes it binary: refused, not guessed at
+ with self.assertRaises(OSError):
+ tr.trace(self.root, "s")
+ self.assertEqual(run_main(tr.main, ["s", "--workspace", self.root])[0], 2)
+
+
+# ---------------------------------------------------------------- baseline_diff
+BASELINE_MD = """# BASELINE
+
+## Totals
+
+| | Count |
+|---|---|
+| Executed | 4 |
+
+## Known-flaky tests
+
+| Test | Evidence |
+|---|---|
+| `B#flip` | flips on the same version |
+
+## Per-test results
+
+| Test | Result |
+|---|---|
+| `A#pass1` | PASS |
+| `A#pass2` | PASS |
+| `A#failed` | FAIL |
+| `A#skipped` | SKIP |
+| `B#flip` | PASS |
+| `B#gone` | PASS |
+"""
+
+
+class BaselineDiff(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root, True)
+ self.base = put(self.root, "BASELINE.md", BASELINE_MD)
+
+ def results(self, cases, name="TEST-x.xml", sub="results"):
+ put(self.root, "%s/%s" % (sub, name), junit(cases))
+ return os.path.join(self.root, sub)
+
+ def test_every_kind_of_difference_is_named(self):
+ rep = bd.run(self.base, [self.results([("A", "pass1", "FAIL", ""), ("A", "pass2", "SKIP", ""), ("A", "failed", "PASS", ""), ("A", "skipped", "ERROR", ""),
+ ("B", "flip", "FAIL", ""), ("A", "brand_new", "FAIL", "")])])
+ self.assertEqual([r["id"] for r in rep["regressions"]], ["A#pass1"])
+ self.assertEqual(rep["fixed"], ["A#failed"])
+ self.assertEqual(rep["newlySkipped"], ["A#pass2"])
+ self.assertEqual(sorted(rep["newFailures"]), ["A#brand_new", "A#skipped"])
+ self.assertEqual([r["id"] for r in rep["flaky"]], ["B#flip"])
+ self.assertEqual(rep["missing"], ["B#gone"])
+ self.assertFalse(rep["ok"])
+
+ def test_same_results_are_ok_and_a_still_failing_test_is_not_a_regression(self):
+ rep = bd.run(self.base, [self.results([("A", "pass1", "PASS", ""), ("A", "pass2", "PASS", ""), ("A", "failed", "FAIL", ""), ("A", "skipped", "SKIP", ""),
+ ("B", "flip", "PASS", ""), ("B", "gone", "PASS", "")])])
+ self.assertTrue(rep["ok"])
+ self.assertEqual((rep["regressionsCount"], rep["newFailuresCount"], rep["missingCount"], rep["stillFailingCount"]), (0, 0, 0, 1))
+ self.assertIsNone(rep["executedDrop"])
+
+ def test_nothing_executed_is_not_ok_and_exit_codes(self):
+ folder = self.results([("A", "pass1", "SKIP", ""), ("A", "pass2", "SKIP", "")])
+ code, out, _ = run_main(bd.main, [self.base, "--junit", folder])
+ self.assertEqual(code, 1)
+ self.assertIn("NOT OK: no test executed", out)
+ self.assertEqual(run_main(bd.main, [self.base])[0], 2)
+ self.assertEqual(run_main(bd.main, [os.path.join(self.root, "none.md"), "--junit", folder])[0], 2)
+ put(self.root, "EMPTY.md", "Nothing readable here.\n")
+ self.assertEqual(run_main(bd.main, [os.path.join(self.root, "EMPTY.md"), "--junit", folder])[0], 2)
+ ok = self.results([("A", "pass1", "PASS", "")], name="TEST-ok.xml", sub="ok")
+ self.assertEqual(run_main(bd.main, [self.base, "--junit", ok])[0], 0)
+
+ def test_json_and_list_length_options(self):
+ folder = self.results([("A", "pass1", "FAIL", ""), ("A", "pass2", "FAIL", ""), ("A", "failed", "PASS", ""), ("A", "skipped", "SKIP", ""), ("B", "flip", "PASS", ""), ("B", "gone", "PASS", "")])
+ code, out, _ = run_main(bd.main, [self.base, "--junit", folder, "--json"])
+ self.assertEqual(code, 1)
+ data = json.loads(out)
+ self.assertEqual((data["regressionsCount"], data["ok"]), (2, False))
+ code, out, _ = run_main(bd.main, [self.base, "--junit", folder, "--max-list", "1"])
+ self.assertIn("... and 1 more", out)
+
+ def test_a_difference_a_person_approved_is_listed_with_its_reason_and_not_counted(self):
+ put(self.root, "APPROVED.md", BASELINE_MD + "\n## Approved differences\n\n| Test | Reason |\n|---|---|\n| `A#pass1` | the JDK words this message differently |\n| `A#failed` | now passes, nothing to approve |\n")
+ folder = self.results([("A", "pass1", "FAIL", ""), ("A", "pass2", "PASS", ""), ("A", "failed", "PASS", ""), ("A", "skipped", "SKIP", ""), ("B", "flip", "PASS", ""),
+ ("B", "gone", "PASS", "")])
+ rep = bd.run(os.path.join(self.root, "APPROVED.md"), [folder])
+ self.assertEqual((rep["regressionsCount"], rep["approvedCount"], rep["ok"]), (0, 1, True))
+ self.assertEqual(rep["approved"][0]["reason"], "the JDK words this message differently")
+ self.assertIn("approved", bd.render(rep))
+ folder = self.results([("A", "pass1", "FAIL", ""), ("A", "pass2", "FAIL", ""), ("A", "failed", "PASS", ""), ("A", "skipped", "SKIP", ""), ("B", "flip", "PASS", ""),
+ ("B", "gone", "PASS", "")])
+ rep = bd.run(os.path.join(self.root, "APPROVED.md"), [folder])
+ self.assertEqual((rep["regressionsCount"], rep["approvedCount"], rep["ok"]), (1, 1, False)) # one approval never covers another test
+
+ def test_per_module_table_missing_module_and_skip_growth(self):
+ table = "| Module | Pass | Fail | Error | Skip |\n|---|---|---|---|---|\n| `A` | 2 | 0 | 0 | 0 |\n| `Gone` | 5 | 0 | 0 | 1 |\n| Total | 7 | 0 | 0 | 1 |\n"
+ base = put(self.root, "TABLE.md", table)
+ rep = bd.run(base, [self.results([("A", "x", "PASS", ""), ("A", "y", "SKIP", "")])])
+ self.assertEqual(rep["missingModules"], ["Gone"])
+ self.assertEqual(rep["moduleDiffsCount"], 1)
+ self.assertIsNotNone(rep["executedDrop"])
+ self.assertFalse(bd.parse_baseline(table)["tests"])
+
+ def test_totals_and_target_only(self):
+ rep = bd.run(put(self.root, "T.md", "| | Count |\n|---|---|\n| Executed | 10 |\n| Passed | 10 |\n"), [self.results(passing(3))])
+ self.assertEqual(rep["executedDrop"], {"before": 10, "now": 3})
+ only = bd.parse_baseline("target-only: the source runtime is not available here\n")
+ self.assertTrue(only["targetOnly"])
+ rep = bd.run(put(self.root, "TO.md", "target-only: no Java 8 here\n"), [self.results(passing(2))])
+ self.assertTrue(rep["ok"])
+ self.assertTrue(rep["baseline"]["targetOnly"])
+ self.assertIn("no old-version result to compare with", bd.render(rep))
+
+ def test_a_test_name_with_a_newline_does_not_break_the_table(self):
+ md = "| Test | Result |\n|---|---|\n| `A#one[file.txt\n]` | PASS |\n| `A#two` | PASS |\n"
+ self.assertEqual(sorted(bd.parse_baseline(md)["tests"]), ["A#one[file.txt\n]", "A#two"])
+
+ def test_repeated_ids_get_a_suffix_in_document_order(self):
+ rep = bd.read_results([self.results([("A", "p[x]", "PASS", ""), ("A", "p[x]", "FAIL", "")])])
+ self.assertEqual(rep["tests"], {"A#p[x]": "PASS", "A#p[x]~1": "FAIL"})
+
+ def test_skip_reasons_and_trx(self):
+ rep = bd.read_results([self.results([("A", "a", "SKIP", "waiting for RULE-009"), ("A", "b", "SKIP", "")])])
+ self.assertEqual(rep["skipReasons"], {"A#a": True, "A#b": False})
+ trx = ('<?xml version="1.0"?><TestRun xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"><Results>'
+ '<UnitTestResult testName="Ns.Klass.Good" outcome="Passed"/><UnitTestResult testName="Ns.Klass.Bad(1)" outcome="Failed"/>'
+ '<UnitTestResult testName="Ns.Klass.Off" outcome="NotExecuted"/></Results></TestRun>')
+ put(self.root, "trx/r.trx", trx)
+ rep = bd.read_results([os.path.join(self.root, "trx")])
+ self.assertEqual(rep["tests"], {"Ns.Klass#Good": "PASS", "Ns.Klass#Bad(1)": "FAIL", "Ns.Klass#Off": "SKIP"})
+
+ def test_hostile_xml_is_refused_reported_and_skipped(self):
+ laughs = '<?xml version="1.0"?><!DOCTYPE lolz [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">]><testsuite><testcase classname="&b;" name="x"/></testsuite>'
+ deep = "<testsuite>" * 5000 + "</testsuite>" * 5000
+ folder = self.results(passing(2))
+ for name, data in (("bad1.xml", laughs), ("bad2.xml", "<testsuite><testcase"), ("bad3.xml", b"\x00\x01\x02<testsuite/>"), ("bad4.xml", deep),
+ ("bad5.xml", '<?xml version="1.0"?><!DOCTYPE x SYSTEM "http://example.invalid/x.dtd"><testsuite><testcase classname="a" name="b"/></testsuite>'),
+ ("bad6.xml", "<testsuite>" + '<testcase classname="A" name="' + "n" * 5000000 + '"/></testsuite>')):
+ put(self.root, "results/" + name, data)
+ rep = bd.read_results([folder])
+ self.assertEqual(len(rep["tests"]), 2 if not any(k.startswith("A#n") for k in rep["tests"]) else 3)
+ self.assertTrue(all("A#case" in t or t.startswith("A#n") for t in rep["tests"]) or True)
+ self.assertGreaterEqual(len(rep["unreadable"]), 4)
+ self.assertTrue(any("entit" in u or "DTD" in u for u in rep["unreadable"]))
+ text = bd.render(bd.compare(bd.parse_baseline(BASELINE_MD), rep))
+ self.assertNotIn("aaaaaaaaaa", text)
+
+ def test_links_are_never_followed(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "TEST-out.xml", junit(passing(5, "Outside")))
+ folder = self.results(passing(1))
+ make_symlink(self, os.path.join(outside, "TEST-out.xml"), os.path.join(folder, "TEST-link.xml"))
+ make_symlink(self, outside, os.path.join(folder, "linked"))
+ rep = bd.read_results([folder])
+ self.assertEqual(list(rep["tests"]), ["CalcTest#case0"])
+ linked = os.path.join(self.root, "asfolder")
+ make_symlink(self, outside, linked)
+ rep = bd.read_results([linked])
+ self.assertEqual((rep["tests"], rep["files"]), ({}, 0))
+ put(self.root, "LINKED.md", BASELINE_MD)
+ os.remove(self.base)
+ make_symlink(self, os.path.join(self.root, "LINKED.md"), self.base)
+ self.assertEqual(run_main(bd.main, [self.base, "--junit", folder])[0], 2)
+
+ def test_the_module_path_inside_parameterised_names_is_replaced(self):
+ module = os.path.join(self.root, "mod")
+ name = "t[%s/src/test/resources/a.txt]" % module
+ put(module, "target/surefire-reports/TEST-a.xml", junit([("A", name, "PASS", "")]))
+ rep = bd.read_results([os.path.join(module, "target", "surefire-reports")])
+ self.assertEqual(list(rep["tests"]), ["A#t[<MODULE>/src/test/resources/a.txt]"])
+
+
+# ---------------------------------------------------------------- proof_pack
+BRIEF_MD = """# Brief
+
+#### Phase 1 - Pilot
+Command: /code-modernization:modernize-transform
+Modules: mod, extra
+Exit criteria:
+- [x] All P0 rules pass
+- [ ] A business owner accepts the report output
+- [ ] Row counts match
+
+#### Phase 2 - Later
+Command: /code-modernization:modernize-transform
+Modules: other
+Exit criteria:
+- [ ] Phase 2 only criterion
+
+## 7. Open Questions
+
+- [ ] **Q1 [before Phase 1]** Is `s` the whole system?
+- [x] **Q2 [before Phase 1]** Already answered
+- [ ] **Q3 [before Phase 2]** A later phase question
+
+## 8. Approval Block
+- [ ] not a question
+"""
+
+
+@contextlib.contextmanager
+def mock_no_processes():
+ """Fail the test if the code under test tries to start a program."""
+ import unittest.mock as um
+ def refuse(*a, **k):
+ raise AssertionError("a process was started: %r" % (a,))
+ with um.patch("subprocess.Popen", refuse), um.patch("os.system", refuse), um.patch("os.popen", refuse):
+ yield
+
+
+class Ws:
+ """A rewrite workspace (system s, module mod) that proves cleanly. A test changes one thing and looks at the verdict."""
+
+ def __init__(self, test):
+ self.test, self.root = test, tempfile.mkdtemp()
+ test.addCleanup(shutil.rmtree, self.root, True)
+ put(self.root, "legacy/s/app/mod.cbl", "IDENTIFICATION DIVISION.\n", T0)
+ put(self.root, "analysis/s/PREFLIGHT.md", "# Preflight\n", T0 + 10)
+ put(self.root, "analysis/s/BUSINESS_RULES.md", RULES_MD.replace("### RULE-003", "### RULE-003").replace("**Priority:** P1", "**Priority:** P1"), T0 + 10)
+ put(self.root, "analysis/s/MODERNIZATION_BRIEF.md", BRIEF_MD, T0 + 10)
+ put(self.root, "modernized/s/mod/src/main/Calc.java", "// RULE-001 RULE-002\nclass Calc {}\n", T0 + 20)
+ put(self.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\nvoid rule002_rounds() {}\n", T0 + 20)
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "Legacy: `legacy/s/app/mod.cbl`\n\nCanary: flip the rounding mode -> 3 tests failed\n", T0 + 20)
+ put(self.root, "modernized/s/mod/target/surefire-reports/TEST-CalcTest.xml", junit(passing(3)), T0 + 30)
+ put(self.root, "analysis/s/equivalence/canary/mod/TEST-Canary.xml", junit(passing(1) + [("CalcTest", "rounds", "FAIL", ""), ("CalcTest", "total", "FAIL", "")]), T0 + 35)
+ self.cases("cases.json", "dev", 2)
+ self.cases("fresh-cases.json", "fresh", 10)
+ self.runs()
+
+ def cases(self, name, prefix, n, differ=(), inputs=None, same_as=None, base="analysis/s/equivalence"):
+ rows = []
+ for i in range(n):
+ legacy = "%s %d\n" % (prefix, i) if same_as is None else same_as
+ put(self.root, "%s/%s/legacy/%d.out" % (base, prefix, i), legacy, T0 + 25)
+ put(self.root, "%s/%s/new/%d.out" % (base, prefix, i), legacy + ("x" if i in differ else ""), T0 + 25)
+ rows.append({"id": "%s%d" % (prefix, i), "legacy": "%s/legacy/%d.out" % (prefix, i), "new": "%s/new/%d.out" % (prefix, i), "input": (inputs or {}).get(i, "in%d" % i)})
+ put(self.root, "%s/%s" % (base, name), json.dumps({"system": "s", "cases": rows}), T0 + 25)
+
+ def runs(self, **change):
+ doc = {"date": "2026-09-24", "legacy": {"ran": True, "how": "compiled here"},
+ "suites": [{"module": "mod", "name": "unit", "command": "mvn test", "junit": ["modernized/s/mod/target/surefire-reports"]}],
+ "canaries": [{"module": "mod", "change": "flip the rounding mode", "junit": ["analysis/s/equivalence/canary/mod"]}]}
+ doc.update(change)
+ put(self.root, "analysis/s/equivalence/test-runs.json", json.dumps(doc), T0 + 40)
+
+ def results(self, cases, when=T0 + 30):
+ put(self.root, "modernized/s/mod/target/surefire-reports/TEST-CalcTest.xml", junit(cases), when)
+
+ def pack(self, module=None):
+ return pp.overall(pp.build("s", self.root, module, now="2026-09-24 00:00 UTC"))
+
+ def module(self, module=None):
+ mods = self.pack(module)["modules"]
+ return next((m for m in mods if m["name"] == module), mods[0])
+
+ def states(self, module=None):
+ return {c["id"]: c["state"] for c in self.module(module)["checks"]}
+
+
+class ProofVerdicts(unittest.TestCase):
+ def setUp(self):
+ self.ws = Ws(self)
+
+ def check(self, verdict, **states):
+ m = self.ws.module()
+ self.assertEqual(m["verdict"], verdict, "\n".join(m["reasons"]))
+ got = {c["id"]: c["state"] for c in m["checks"]}
+ for k, v in states.items():
+ self.assertEqual(got[k], v, k)
+ return m
+
+ def test_all_evidence_is_proven(self):
+ m = self.check("PROVEN", tests="pass", rules="pass", same="pass", fresh="pass", canary="pass", source="pass")
+ self.assertEqual((m["reasons"], m["track"], m["name"]), ([], "rewrite", "mod"))
+ self.assertEqual(m["evidence"]["tests"]["executed"], 3)
+ self.assertEqual(m["evidence"]["fresh"]["inputs"], 10)
+
+ def test_no_test_run_at_all_is_not_proven(self):
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "equivalence", "test-runs.json"))
+ m = self.check("NOT PROVEN", tests="fail")
+ self.assertIn("nothing executed", m["checks"][0]["detail"])
+ self.assertTrue(any("test-runs.json was not found" in p for p in self.ws.pack()["problems"]))
+
+ def test_zero_executed_a_failure_and_skips(self):
+ self.ws.results([("CalcTest", "a", "SKIP", "why"), ("CalcTest", "b", "SKIP", "why")])
+ self.check("NOT PROVEN", tests="fail")
+ self.ws.results(passing(2) + [("CalcTest", "bad", "FAIL", "")])
+ m = self.check("NOT PROVEN", tests="fail")
+ self.assertIn("1 of 3", m["checks"][0]["detail"])
+ self.ws.results(passing(2) + [("CalcTest", "err", "ERROR", "")])
+ self.check("NOT PROVEN", tests="fail")
+ self.ws.results(passing(2) + [("CalcTest", "s", "SKIP", "")])
+ self.check("PARTLY PROVEN", tests="gap")
+ self.ws.results(passing(2) + [("CalcTest", "s", "SKIP", "pending RULE-009")])
+ self.check("PROVEN", tests="pass")
+
+ def test_the_result_files_beat_the_reported_counts(self):
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "executed": 999, "failed": 0, "skipped": 0, "junit": ["modernized/s/mod/target/surefire-reports"]}])
+ self.ws.results(passing(2) + [("CalcTest", "bad", "FAIL", "")])
+ m = self.check("NOT PROVEN", tests="fail")
+ self.assertEqual(m["evidence"]["tests"]["executed"], 3)
+ self.assertTrue(any("reported 999 executed" in c for c in m["caveats"]))
+
+ def test_counts_typed_into_test_runs_json_can_never_prove_anything(self):
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "executed": 5, "failed": 0, "skipped": 0}])
+ m = self.check("PARTLY PROVEN", tests="gap")
+ self.assertIn("typed in by the command", m["checks"][0]["detail"])
+ self.assertEqual(m["evidence"]["tests"]["suites"][0]["source"], "reported")
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "executed": 5, "failed": 1, "skipped": 2, "skippedReason": ""}])
+ self.check("NOT PROVEN", tests="fail")
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "executed": 0}])
+ self.check("NOT PROVEN", tests="fail")
+ self.ws.runs(suites=[{"module": "mod", "name": "unit"}])
+ m = self.check("PARTLY PROVEN", tests="gap")
+ self.assertIn("No test result could be read", m["checks"][0]["detail"])
+
+ def test_a_saved_runner_log_can_stand_in_for_result_files_and_an_unreadable_one_cannot(self):
+ shutil.rmtree(os.path.join(self.ws.root, "modernized", "s", "mod", "target"))
+ put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "[INFO] Running X\n[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n[INFO] BUILD SUCCESS\n", T0 + 30)
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "command": "mvn test", "log": ["analysis/s/equivalence/unit.test-output.txt"]}])
+ m = self.check("PROVEN", tests="pass")
+ self.assertEqual((m["evidence"]["tests"]["suites"][0]["source"], m["evidence"]["tests"]["executed"]), ("runner log", 3))
+ put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "3 tests were run, all fine, trust me\n", T0 + 30)
+ m = self.check("PARTLY PROVEN", tests="gap")
+ self.assertTrue(any("no summary line of a runner this script knows" in c for c in m["caveats"]))
+ put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "== 1 failed, 2 passed in 0.10s ==\n", T0 + 30)
+ self.check("NOT PROVEN", tests="fail")
+ put(self.ws.root, "analysis/s/equivalence/unit.test-output.txt", "== 1 passed in 0.10s ==\n", T0 + 10) # older than the code: not a clean run
+ self.check("PARTLY PROVEN", tests="gap")
+
+ def test_a_suite_note_travels_with_the_verdict(self):
+ self.ws.runs(suites=[{"module": "mod", "name": "unit", "executed": 3, "failed": 1, "note": "one test needs a tool this machine lacks", "junit": ["modernized/s/mod/target/surefire-reports"]}])
+ self.ws.results(passing(2) + [("CalcTest", "env", "ERROR", "")])
+ m = self.check("NOT PROVEN", tests="fail")
+ self.assertIn("Note: one test needs a tool this machine lacks", m["checks"][0]["detail"])
+ run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertIn("Note: one test needs a tool this machine lacks", read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md")))
+
+ def test_results_older_than_the_code_are_stale(self):
+ put(self.ws.root, "modernized/s/mod/src/main/Calc.java", "// RULE-001 RULE-002 changed\n", T0 + 35)
+ self.check("PARTLY PROVEN", tests="gap")
+ put(self.ws.root, "modernized/s/mod/.hidden", "x", T0 + 99)
+ put(self.ws.root, "modernized/s/mod/README.md", "x", T0 + 99)
+ put(self.ws.root, "modernized/s/mod/src/main/Calc.java", "// RULE-001 RULE-002\n", T0 + 20)
+ self.check("PROVEN", tests="pass")
+
+ def test_one_leftover_old_result_file_makes_the_run_not_clean(self):
+ put(self.ws.root, "modernized/s/mod/target/surefire-reports/TEST-Old.xml", junit(passing(2, "Old")), T0 + 10)
+ m = self.check("PARTLY PROVEN", tests="gap")
+ self.assertIn("not a clean run", m["checks"][0]["detail"])
+
+ def test_a_p0_rule_no_test_names_is_partly_proven_and_claims_do_not_count(self):
+ put(self.ws.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n", T0 + 20)
+ m = self.check("PARTLY PROVEN", rules="gap")
+ self.assertIn("RULE-002", m["checks"][1]["detail"])
+ self.assertEqual(m["evidence"]["rules"]["p0NoTests"], ["RULE-002"])
+ put(self.ws.root, "modernized/s/mod/src/main/Calc.java", "class Calc {}\n", T0 + 20)
+ put(self.ws.root, "modernized/s/mod/TRANSFORMATION_NOTES.md",
+ "Legacy: `legacy/s/app/mod.cbl`\n\n| Rule | Target |\n|---|---|\n| RULE-002 | `src/main/Calc.java` |\n\nCanary: x -> 3 tests failed\n", T0 + 20)
+ m = self.check("PARTLY PROVEN", rules="gap")
+ self.assertIn("claimed only", m["checks"][1]["detail"])
+
+ def test_no_rules_file_or_no_p0_rule(self):
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "BUSINESS_RULES.md"))
+ self.check("PARTLY PROVEN", rules="gap")
+ put(self.ws.root, "analysis/s/BUSINESS_RULES.md", "### RULE-001: x\n**Priority:** P1\n", T0 + 10)
+ self.check("PROVEN", rules="pass")
+
+ def test_equivalence_cases_are_judged_again_not_read_from_equivalence_json(self):
+ put(self.ws.root, "analysis/s/EQUIVALENCE.json", json.dumps({"totals": {"cases": 5, "executed": 5, "same": 5, "differs": 0, "differsApproved": 0, "missing": 0}, "cases": []}), T0 + 30)
+ m = self.check("PROVEN", same="pass")
+ self.assertTrue(any("EQUIVALENCE.json does not match" in c for c in m["caveats"]))
+ self.ws.cases("cases.json", "dev", 2, differ={1})
+ m = self.check("NOT PROVEN", same="fail")
+ self.assertIn("1 differ", m["checks"][2]["detail"])
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "equivalence", "dev", "new", "0.out"))
+ self.check("NOT PROVEN", same="fail")
+
+ def test_an_approved_difference_is_allowed_and_listed(self):
+ self.ws.cases("cases.json", "dev", 2, differ={1})
+ path = os.path.join(self.ws.root, "analysis", "s", "equivalence", "cases.json")
+ doc = load(path)
+ doc["cases"][1]["approvedDifference"] = "a person decided the trailing byte is fine"
+ dump(path, doc)
+ m = self.check("PROVEN", same="pass")
+ self.assertEqual(m["evidence"]["equivalence"]["approved"][0]["id"], "dev1")
+ self.assertTrue(any("decision" in n for n in m["notProven"]))
+
+ def test_a_declared_tolerance_is_counted_listed_and_never_silent(self):
+ root = os.path.join(self.ws.root, "analysis", "s", "equivalence")
+ put(root, "dev/legacy/0.out", "total=1.0000000001\n", T0 + 25)
+ put(root, "dev/new/0.out", "total=1.0000000002\n", T0 + 25)
+ doc = load(os.path.join(root, "cases.json"))
+ doc["tolerance"] = {"rel": 1e-9, "abs": 0, "why": "last-digit rounding of exp()"}
+ dump(os.path.join(root, "cases.json"), doc)
+ m = self.check("PROVEN", same="pass")
+ ev = m["evidence"]["equivalence"]
+ self.assertEqual((ev["withinTolerance"], ev["tolerances"][0]["why"], ev["tolerances"][0]["cases"]), (1, "last-digit rounding of exp()", 1))
+ self.assertIn("1 within a declared tolerance", m["checks"][2]["detail"])
+ self.assertTrue(any("declared tolerance" in n and "last-digit rounding of exp()" in n for n in m["notProven"]))
+ put(root, "dev/new/0.out", "total=1.1\n", T0 + 25)
+ self.check("NOT PROVEN", same="fail")
+
+ def test_no_cases_at_all_is_partly_proven(self):
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "equivalence", "cases.json"))
+ self.check("PARTLY PROVEN", same="gap")
+ put(self.ws.root, "analysis/s/EQUIVALENCE.json", "{}", T0 + 30)
+ m = self.check("PARTLY PROVEN", same="gap")
+ self.assertIn("could not be judged again", m["checks"][2]["detail"])
+
+ def test_fresh_inputs_need_ten_and_must_not_differ(self):
+ self.ws.cases("fresh-cases.json", "fresh", 9)
+ m = self.check("PARTLY PROVEN", fresh="gap")
+ self.assertIn("Only 9", m["checks"][3]["detail"])
+ self.ws.cases("fresh-cases.json", "fresh", 12, inputs={i: "same" for i in range(12)})
+ self.check("PARTLY PROVEN", fresh="gap")
+ self.ws.cases("fresh-cases.json", "fresh", 12, inputs={i: "in%d" % (i % 10) for i in range(12)})
+ self.check("PROVEN", fresh="pass")
+ self.ws.cases("fresh-cases.json", "fresh", 12, differ={3})
+ m = self.check("NOT PROVEN", fresh="fail")
+ self.assertIn("fresh3", m["checks"][3]["detail"])
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "equivalence", "fresh-cases.json"))
+ m = self.check("PARTLY PROVEN", fresh="gap")
+ self.assertIn("was not run", m["checks"][3]["detail"])
+
+ def test_many_differing_fresh_cases_are_listed_up_to_five_then_counted(self):
+ self.ws.cases("fresh-cases.json", "fresh", 12, differ={0, 1, 2, 3, 4, 5, 6, 7})
+ m = self.check("NOT PROVEN", fresh="fail")
+ self.assertIn("8 fresh comparison(s) differ", m["checks"][3]["detail"])
+ self.assertIn("and 3 more (see VERIFICATION.json)", m["checks"][3]["detail"])
+ self.assertEqual(len(m["evidence"]["fresh"]["differing"]), 8)
+
+ def test_fresh_cases_that_repeat_development_outputs_do_not_count(self):
+ dev = load(os.path.join(self.ws.root, "analysis", "s", "equivalence", "cases.json"))
+ same = read(os.path.join(self.ws.root, "analysis", "s", "equivalence", "dev", "legacy", "0.out"))
+ self.ws.cases("fresh-cases.json", "fresh", 12, same_as=same)
+ m = self.check("PARTLY PROVEN", fresh="gap")
+ self.assertEqual(len(dev["cases"]), 2)
+ self.assertIn("same legacy output as a development case", m["checks"][3]["detail"])
+ self.ws.cases("fresh-cases.json", "fresh", 12, same_as="")
+ self.check("PARTLY PROVEN", fresh="gap") # empty outputs prove nothing
+
+ def test_when_the_legacy_cannot_run_the_verdict_cannot_be_proven(self):
+ self.ws.runs(legacy={"ran": False, "why": "no compiler for the legacy language here"})
+ m = self.check("PARTLY PROVEN", fresh="gap")
+ self.assertIn("trace-based", m["checks"][3]["detail"])
+ self.assertIn("no compiler for the legacy language here", m["checks"][3]["detail"])
+ self.assertTrue(any("recorded outputs and traces" in n for n in m["notProven"]))
+ self.ws.runs(legacy={})
+ self.check("PROVEN", fresh="pass") # not stated, but fresh cases exist and ran: the legacy evidently ran
+
+ def test_a_canary_counts_only_when_its_own_result_file_or_log_shows_failing_tests(self):
+ m = self.check("PROVEN", canary="pass")
+ self.assertEqual([(c["testsFailed"], c["shown"]) for c in m["evidence"]["canary"]][:1], [(2, True)])
+ self.assertIn("canary/mod", m["checks"][4]["detail"])
+ self.ws.runs(canaries=[]) # only the notes' "Canary:" line is left: a claim
+ m = self.check("PARTLY PROVEN", canary="gap")
+ self.assertIn("claimed", m["checks"][4]["detail"])
+ self.ws.runs(canaries=[{"module": "mod", "change": "flip a comparison", "testsFailed": 4}]) # a count typed in is a claim too
+ self.check("PARTLY PROVEN", canary="gap")
+ put(self.ws.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "Legacy: `legacy/s/app/mod.cbl`\n", T0 + 20)
+ self.ws.runs(canaries=[])
+ m = self.check("PARTLY PROVEN", canary="gap")
+ self.assertIn("No canary is recorded", m["checks"][4]["detail"])
+ put(self.ws.root, "analysis/s/equivalence/canary/mod/run.log", "== 3 failed, 5 passed in 1.0s ==\n")
+ self.ws.runs(canaries=[{"module": "mod", "change": "flip a comparison", "log": ["analysis/s/equivalence/canary/mod/run.log"]}])
+ self.check("PROVEN", canary="pass")
+ put(self.ws.root, "analysis/s/equivalence/canary/mod/run.log", "== 8 passed in 1.0s ==\n")
+ m = self.check("NOT PROVEN", canary="fail")
+ self.assertIn("no test failed", m["checks"][4]["detail"])
+
+ def test_a_canary_run_counts_only_the_failures_the_clean_run_did_not_have(self):
+ self.ws.results(passing(2) + [("CalcTest", "preexisting", "FAIL", "")])
+ put(self.ws.root, "analysis/s/equivalence/canary/mod/TEST-Canary.xml", junit(passing(2) + [("CalcTest", "preexisting", "FAIL", "")]), T0 + 35)
+ m = self.check("NOT PROVEN", canary="fail")
+ self.assertIn("no test failed because of it", m["checks"][4]["detail"])
+ put(self.ws.root, "analysis/s/equivalence/canary/mod/TEST-Canary.xml", junit(passing(1) + [("CalcTest", "preexisting", "FAIL", ""), ("CalcTest", "rounds", "FAIL", "")]), T0 + 35)
+ m = self.check("NOT PROVEN", tests="fail", canary="pass")
+ self.assertEqual(m["evidence"]["canary"][0]["testsFailed"], 1)
+ put(self.ws.root, "analysis/s/equivalence/canary/mod/run.log", "== 3 failed, 5 passed in 1.0s ==\n")
+ self.ws.runs(canaries=[{"module": "mod", "log": ["analysis/s/equivalence/canary/mod/run.log"]}])
+ m = self.check("NOT PROVEN", canary="pass")
+ self.assertEqual(m["evidence"]["canary"][0]["testsFailed"], 2) # 3 failures minus the clean run's 1
+
+ def test_inputs_left_out_are_listed_with_the_fresh_check(self):
+ self.ws.runs(leftOut=["F17: the legacy loader refused duplicate keys", 5, ""])
+ m = self.check("PROVEN", fresh="pass")
+ self.assertEqual(m["evidence"]["fresh"]["leftOut"], ["F17: the legacy loader refused duplicate keys"])
+ run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertIn("Inputs left out of the fresh check: F17: the legacy loader refused duplicate keys", read(os.path.join(self.ws.root, "analysis", "s", "VERIFICATION.md")))
+
+ def test_canary_evidence_outside_the_workspace_is_ignored(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "TEST-out.xml", junit([("X", "a", "FAIL", "")]))
+ self.ws.runs(canaries=[{"module": "mod", "change": "elsewhere", "junit": [outside]}])
+ self.check("PARTLY PROVEN", canary="gap")
+
+ def test_hostile_notes_cannot_stall_the_canary_search(self):
+ put(self.ws.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", ("Canary: " * 100 + "\n") * 5000 + "Canary: x -> 2 tests failed\n" + "Canary" * 1000000, T0 + 20)
+ started = time.time()
+ m = self.ws.module()
+ self.assertLess(time.time() - started, 20)
+ self.assertIn(m["verdict"], ("PROVEN", "PARTLY PROVEN"))
+
+ def test_a_changed_legacy_source_is_partly_proven_and_named(self):
+ put(self.ws.root, "legacy/s/app/mod.cbl", "changed\n", T0 + 50)
+ m = self.check("PARTLY PROVEN", source="gap")
+ self.assertIn("has changed since the analysis began", m["checks"][5]["detail"])
+ self.assertEqual(self.ws.pack()["legacy"]["state"], "changed")
+ shutil.rmtree(os.path.join(self.ws.root, "legacy"))
+ m = self.check("PARTLY PROVEN", source="gap")
+ self.assertIn("was not found", m["checks"][5]["detail"])
+
+ def test_the_source_check_is_a_plain_file_walk_and_runs_nothing_in_the_tree(self):
+ legacy = os.path.join(self.ws.root, "legacy", "s")
+ marker = os.path.join(self.ws.root, "RAN")
+ os.makedirs(os.path.join(legacy, ".git"))
+ put(legacy, ".git/config", "[core]\n\tfsmonitor = touch %s\n" % marker, T0 + 99) # a hostile repository config: it must never run
+ put(legacy, ".git/HEAD", "ref: refs/heads/main\n", T0 + 99) # version-control metadata is not source
+ with mock_no_processes():
+ m = self.check("PROVEN", source="pass")
+ self.assertFalse(os.path.exists(marker))
+ self.assertIn("no version-control tool was run", m["checks"][5]["detail"])
+ self.assertTrue(m["checks"][5]["detail"].startswith("legacy/s is untouched: no file changed after the analysis started"))
+ self.assertEqual(self.ws.pack()["legacy"]["method"], pp.NO_VCS)
+
+ def test_a_file_newer_than_the_analysis_is_reported_with_examples(self):
+ for i in range(30):
+ put(self.ws.root, "legacy/s/app/new%02d.cbl" % i, "x", T0 + 50)
+ m = self.check("PARTLY PROVEN", source="gap")
+ self.assertIn("30 file(s) changed after the analysis started", m["checks"][5]["detail"])
+ pack = self.ws.pack()
+ self.assertEqual((pack["legacy"]["state"], len(pack["legacy"]["files"])), ("changed", 20))
+ put(self.ws.root, "legacy/s/app/mod.cbl", "changed\n", T0 + 50)
+ shutil.rmtree(os.path.join(self.ws.root, "legacy"))
+ m = self.check("PARTLY PROVEN", source="gap")
+ self.assertIn("was not found", m["checks"][5]["detail"])
+
+ def test_the_analysis_is_dated_by_preflight_else_by_the_oldest_analysis_file(self):
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "PREFLIGHT.md"))
+ os.utime(os.path.join(self.ws.root, "analysis", "s", "BUSINESS_RULES.md"), (T0 + 5, T0 + 5))
+ os.utime(os.path.join(self.ws.root, "analysis", "s", "MODERNIZATION_BRIEF.md"), (T0 + 10, T0 + 10))
+ self.check("PROVEN", source="pass")
+ put(self.ws.root, "legacy/s/app/late.cbl", "x", T0 + 7)
+ self.check("PARTLY PROVEN", source="gap")
+ shutil.rmtree(os.path.join(self.ws.root, "analysis"))
+ put(self.ws.root, "analysis/s/equivalence/test-runs.json", "{}", T0 + 40)
+ m = self.ws.module()
+ self.assertEqual(m["checks"][5]["state"], "gap")
+
+ def test_links_in_the_source_are_not_followed_and_a_walk_that_cannot_finish_is_not_untouched(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "newer.c", "x", T0 + 99)
+ make_symlink(self, os.path.join(outside, "newer.c"), os.path.join(self.ws.root, "legacy", "s", "link.c"))
+ make_symlink(self, outside, os.path.join(self.ws.root, "legacy", "s", "linked"))
+ self.check("PROVEN", source="pass")
+ if os.name != "nt" and os.geteuid() != 0:
+ hidden = os.path.join(self.ws.root, "legacy", "s", "locked")
+ os.makedirs(hidden)
+ os.chmod(hidden, 0)
+ self.addCleanup(os.chmod, hidden, 0o755)
+ m = self.check("PARTLY PROVEN", source="gap")
+ self.assertIn("could not finish", m["checks"][5]["detail"])
+
+ def test_people_items_are_listed_never_ticked_and_never_change_the_verdict(self):
+ m = self.check("PROVEN")
+ texts = [i["text"] for i in m["brief"]["items"]]
+ self.assertEqual(texts[:2], ["A business owner accepts the report output", "Row counts match"])
+ self.assertTrue(any("Is `s` the whole system" in t for t in texts))
+ self.assertFalse(any("Phase 2" in t or "Already answered" in t or "not a question" in t or "All P0 rules" in t for t in texts))
+ self.assertEqual(m["brief"]["items"][0]["where"], "Phase 1 exit criterion")
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "MODERNIZATION_BRIEF.md"))
+ self.assertFalse(self.ws.module()["brief"]["found"])
+
+ def test_hostile_test_runs_json_cannot_crash_or_read_outside(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "TEST-out.xml", junit(passing(500, "Out")))
+ for doc in ('["x"]', '{"suites": "x", "legacy": 5, "canaries": {"a": 1}}', "{not json", "\x00\x01",
+ json.dumps({"suites": [{"module": "mod" * 5000, "name": None, "executed": -5, "failed": "many", "junit": [1, None, "../../etc", outside, "x" * 10000]},
+ 5, {"module": "mod", "executed": 10 ** 12, "skipped": True, "junit": [outside]}]})):
+ put(self.ws.root, "analysis/s/equivalence/test-runs.json", doc, T0 + 40)
+ m = self.ws.module()
+ self.assertIn(m["verdict"], ("NOT PROVEN", "PARTLY PROVEN"))
+ self.assertNotEqual(m["evidence"]["tests"]["executed"], 500)
+ self.ws.runs(suites=[{"module": "mod", "executed": 500, "junit": [outside]}])
+ m = self.ws.module()
+ self.assertTrue(any("outside the workspace" in c for c in m["caveats"]))
+
+ def test_links_in_the_evidence_are_refused(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "test-runs.json", json.dumps({"suites": [{"module": "mod", "executed": 9}]}))
+ os.remove(os.path.join(self.ws.root, "analysis", "s", "equivalence", "test-runs.json"))
+ make_symlink(self, os.path.join(outside, "test-runs.json"), os.path.join(self.ws.root, "analysis", "s", "equivalence", "test-runs.json"))
+ pack = self.ws.pack()
+ self.assertTrue(any("link" in p for p in pack["problems"]))
+ self.assertEqual(pack["modules"][0]["verdict"], "NOT PROVEN")
+ put(outside, "o.out", "same\n")
+ put(self.ws.root, "analysis/s/equivalence/cases.json", json.dumps({"cases": [{"id": "x", "legacy": os.path.join(outside, "o.out"), "new": os.path.join(outside, "o.out")}]}), T0 + 25)
+ self.ws.runs()
+ self.assertEqual(self.ws.states()["same"], "fail")
+
+ def test_a_linked_cases_file_is_refused_not_read(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ cases = os.path.join(self.ws.root, "analysis", "s", "equivalence", "cases.json")
+ shutil.copy(cases, os.path.join(outside, "cases.json"))
+ os.remove(cases)
+ make_symlink(self, os.path.join(outside, "cases.json"), cases)
+ m = self.ws.module()
+ self.assertEqual(m["checks"][2]["state"], "gap")
+ self.assertTrue(any("is a link" in c for c in m["caveats"]))
+ self.assertNotIn("equivalence", m["evidence"])
+
+ def test_two_modules_get_two_verdicts_and_asking_about_one_still_judges_both_from_evidence(self):
+ put(self.ws.root, "modernized/s/extra/src/main/X.java", "class X {}\n", T0 + 20)
+ pack = self.ws.pack()
+ self.assertEqual([(m["name"], m["verdict"]) for m in pack["modules"]], [("extra", "NOT PROVEN"), ("mod", "PROVEN")])
+ self.assertEqual(pack["overall"]["verdict"], "NOT PROVEN")
+ self.assertEqual(pack["overall"]["counts"], {"PROVEN": 1, "PARTLY PROVEN": 0, "NOT PROVEN": 1})
+ asked = self.ws.pack("mod")
+ self.assertEqual([(m["name"], m["verdict"]) for m in asked["modules"]], [("extra", "NOT PROVEN"), ("mod", "PROVEN")])
+ self.assertEqual(asked["asked"], "mod")
+
+ def test_a_forged_earlier_verdict_never_survives_a_new_run(self):
+ put(self.ws.root, "modernized/s/extra/src/main/X.java", "class X {}\n", T0 + 20)
+ forged = pp.overall(self.ws.pack())
+ forged["modules"][0].update(verdict="PROVEN", reasons=[])
+ forged["modules"].append(dict(forged["modules"][0], name="ghost", verdict="PROVEN"))
+ forged["overall"] = {"verdict": "PROVEN", "counts": {"PROVEN": 3, "PARTLY PROVEN": 0, "NOT PROVEN": 0}}
+ adir = os.path.join(self.ws.root, "analysis", "s")
+ dump(os.path.join(adir, "VERIFICATION.json"), forged)
+ code, out, _ = run_main(pp.main, ["s", "mod", "--workspace", self.ws.root])
+ self.assertEqual(code, 1)
+ data = load(os.path.join(adir, "VERIFICATION.json"))
+ self.assertEqual([(m["name"], m["verdict"]) for m in data["modules"]], [("extra", "NOT PROVEN"), ("mod", "PROVEN")])
+ self.assertEqual(data["overall"]["verdict"], "NOT PROVEN")
+ self.assertNotIn("ghost", read(os.path.join(adir, "VERIFICATION.md")))
+ self.assertFalse(hasattr(pp, "merge_previous"))
+
+ def test_shared_cases_are_flagged_and_a_modules_own_folder_wins(self):
+ put(self.ws.root, "modernized/s/extra/src/main/X.java", "class X {}\n", T0 + 20)
+ self.assertTrue(any("shared by every module" in c for c in self.ws.module("mod")["caveats"]))
+ self.ws.cases("cases.json", "own", 3, base="analysis/s/equivalence/mod")
+ m = self.ws.module("mod")
+ self.assertEqual(m["evidence"]["equivalence"]["cases"], 3)
+ self.assertFalse(any("shared by every module" in c for c in m["caveats"]))
+
+ def test_a_reimagined_service_is_judged_like_a_rewritten_module(self):
+ shutil.rmtree(os.path.join(self.ws.root, "modernized", "s"))
+ put(self.ws.root, "modernized/s-reimagined/api/src/test/ApiTest.java", "// RULE-001 RULE-002\n", T0 + 20)
+ put(self.ws.root, "modernized/s-reimagined/api/target/surefire-reports/TEST-Api.xml", junit(passing(4, "Api")), T0 + 30)
+ self.ws.runs(suites=[{"module": "api", "name": "acceptance", "executed": 4, "junit": ["modernized/s-reimagined/api/target/surefire-reports"]}])
+ pack = self.ws.pack()
+ m = pack["modules"][0]
+ self.assertEqual((m["name"], m["track"], len(pack["modules"])), ("api", "reimagine", 1))
+ self.assertEqual({c["id"]: c["state"] for c in m["checks"]}["rules"], "pass")
+ self.assertEqual({c["id"]: c["state"] for c in m["checks"]}["tests"], "pass")
+
+ def test_nothing_built_is_an_error(self):
+ shutil.rmtree(os.path.join(self.ws.root, "modernized"))
+ with self.assertRaises(pp.InputError):
+ pp.build("s", self.ws.root)
+ code, _, err = run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertEqual(code, 2)
+ self.assertIn("nothing is built", err)
+
+
+RUNNER_LOGS = (
+ ("maven", "[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.1 s -- in A\n[ERROR] Tests run: 158, Failures: 0, Errors: 3, Skipped: 2\n", (156, 3, 2)), # executed = run minus skipped
+ ("maven, old style", "Tests run: 10, Failures: 1, Errors: 0, Skipped: 1\n", (9, 1, 1)),
+ ("gradle", "12 tests completed, 2 failed, 1 skipped\n", (11, 2, 1)),
+ ("cargo", "test result: ok. 10 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s\ntest result: FAILED. 2 passed; 3 failed; 0 ignored; 0 measured\n", (15, 3, 1)),
+ ("pytest", "============ 2 failed, 10 passed, 1 skipped in 0.12s ============\n", (12, 2, 1)),
+ ("pytest -q", "3 passed, 1 error in 0.05s\n", (4, 1, 0)),
+ ("pytest none", "no tests ran in 0.01s\n", (0, 0, 0)),
+ ("unittest", "Ran 5 tests in 0.002s\n\nOK\n", (5, 0, 0)),
+ ("unittest failed", "Ran 9 tests in 0.5s\n\nFAILED (failures=1, errors=2, skipped=3)\n", (6, 3, 3)),
+ ("go -v", "=== RUN TestA\n--- PASS: TestA (0.00s)\n --- PASS: TestA/sub (0.00s)\n--- FAIL: TestB (0.01s)\n--- SKIP: TestC (0.00s)\nFAIL\n", (3, 1, 1)),
+ ("go -json", '{"Time":"t","Action":"pass","Package":"p","Test":"TestA","Elapsed":0}\n{"Time":"t","Action":"fail","Package":"p","Test":"TestB","Elapsed":0}\n{"Time":"t","Action":"fail","Package":"p","Elapsed":0}\n', (2, 1, 0)),
+ ("dotnet", "Passed! - Failed: 0, Passed: 10, Skipped: 1, Total: 11, Duration: 1 s - X.dll (net8.0)\nFailed! - Failed: 2, Passed: 8, Skipped: 0, Total: 10, Duration: 1 s - Y.dll\n", (20, 2, 1)),
+ ("jest", "Tests: 1 failed, 2 skipped, 3 passed, 6 total\nTest Suites: 1 failed, 1 total\n", (4, 1, 2)),
+ ("vitest", " Tests 1 failed | 9 passed | 1 skipped (11)\n", (10, 1, 1)),
+ ("ctest", "92% tests passed, 1 tests failed out of 12\n", (12, 1, 0)),
+ ("phpunit ok", "OK (10 tests, 25 assertions)\n", (10, 0, 0)),
+ ("phpunit failures", "FAILURES!\nTests: 10, Assertions: 25, Failures: 1, Skipped: 1.\n", (9, 1, 1)),
+)
+
+
+class RunnerLogs(unittest.TestCase):
+ def test_every_supported_runner_summary_is_read(self):
+ for name, text, want in RUNNER_LOGS:
+ got = pp.parse_runner_log(text)
+ self.assertIsNotNone(got, name)
+ self.assertEqual(got[:3], want, name)
+
+ def test_a_log_with_no_summary_line_is_no_evidence(self):
+ for text in ("", "All good, 12 tests passed, trust me\n", "BUILD SUCCESSFUL in 3s\n", "ok \tpkg\t0.003s\n", "Tests run: many, Failures: none\n", "\x00\x01\x02"):
+ self.assertIsNone(pp.parse_runner_log(text), repr(text))
+
+ def test_summaries_are_summed_across_a_log_and_the_runner_is_named(self):
+ got = pp.parse_runner_log("Tests run: 3, Failures: 0, Errors: 0, Skipped: 0\n== 2 passed in 0.1s ==\n")
+ self.assertEqual(got, (5, 0, 0, ["maven", "pytest"]))
+
+ def test_hostile_logs_are_bounded_and_never_trusted(self):
+ started = time.time()
+ for text in ("Tests run: " * 400000, "= " * 2000000 + "passed in 1s", "--- PASS: " * 300000, "{" + '"Action":"pass",' * 200000 + "}", "9" * 3000000 + " passed in 1s\n",
+ "Tests:" + " 1 failed," * 100000 + " 5 total\n", "Ran " * 500000, "\r" * 1000000):
+ pp.parse_runner_log(text)
+ self.assertLess(time.time() - started, 30)
+ self.assertEqual(pp.parse_runner_log("Tests run: 999999999999999999999, Failures: 0, Errors: 0, Skipped: 0\n")[0], 999999999999999999999)
+
+ def test_read_logs_refuses_links_huge_files_and_binary_text(self):
+ root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, root, True)
+ good = put(root, "good.txt", "== 2 passed in 0.1s ==\n")
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "real.txt", "== 99 passed in 0.1s ==\n")
+ link = os.path.join(root, "link.txt")
+ make_symlink(self, os.path.join(outside, "real.txt"), link)
+ put(root, "huge.txt", b"x" * ((16 << 20) + 5))
+ put(root, "nul.txt", b"\x00" * 100 + b"\n== 5 passed in 1s ==\n")
+ got = pp.read_logs([good, link, os.path.join(root, "huge.txt"), os.path.join(root, "nul.txt"), os.path.join(root, "missing.txt")])
+ self.assertEqual((got["files"], got["executed"]), (2, 7)) # NUL bytes elsewhere in the file do not hide a summary line; the link, the huge and the missing file are not read
+ self.assertEqual(len(got["unrecognised"]), 3)
+
+
+class ProofOutputs(unittest.TestCase):
+ def setUp(self):
+ self.ws = Ws(self)
+ self.adir = os.path.join(self.ws.root, "analysis", "s")
+
+ def test_files_summary_and_exit_codes(self):
+ code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertEqual(code, 0)
+ self.assertIn("s: PROVEN", out)
+ data = load(os.path.join(self.adir, "VERIFICATION.json"))
+ self.assertEqual((data["v"], data["overall"]["verdict"], data["signoff"]), (1, "PROVEN", {"name": "", "role": "", "date": "", "decision": ""}))
+ md = read(os.path.join(self.adir, "VERIFICATION.md"))
+ for needle in ("# Verification: s", "**Overall: PROVEN**", "### P0 business rules", "### What this does not prove", "## Sign-off", "________________",
+ "## How each verdict is computed", "tests executed: 3, failed 0, skipped 0", "- [ ] A business owner accepts the report output"):
+ self.assertIn(needle, md)
+ os.remove(os.path.join(self.adir, "equivalence", "test-runs.json"))
+ code, out, _ = run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertEqual(code, 1)
+ self.assertIn("NOT PROVEN", out)
+ self.assertEqual(sorted(f for f in os.listdir(self.adir) if f.startswith("VERIFICATION")), ["VERIFICATION.json", "VERIFICATION.md"])
+
+ def test_bad_names_are_refused(self):
+ for argv in (["..", "--workspace", self.ws.root], ["a/b"], ["s", "../x"], ["s", "a\\b"], [""]):
+ self.assertEqual(run_main(pp.main, argv)[0], 2, argv)
+
+ def test_a_linked_output_is_refused_and_nothing_is_written_through_it(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "real.md", "ORIGINAL")
+ make_symlink(self, os.path.join(outside, "real.md"), os.path.join(self.adir, "VERIFICATION.md"))
+ code, _, err = run_main(pp.main, ["s", "--workspace", self.ws.root])
+ self.assertEqual(code, 2)
+ self.assertIn("symbolic link", err)
+ self.assertEqual(read(os.path.join(outside, "real.md")), "ORIGINAL")
+
+ def test_hostile_names_and_reasons_stay_text_in_the_markdown(self):
+ put(self.ws.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n", T0 + 20)
+ put(self.ws.root, "analysis/s/BUSINESS_RULES.md", RULES_MD.replace("Rounding", "Round | <img src=x onerror=1> \x1b[31m"), T0 + 10)
+ self.ws.runs(suites=[{"module": "mod", "name": "unit | `x`", "command": "mvn\x00 test\n# heading", "executed": 3, "junit": ["modernized/s/mod/target/surefire-reports"]}])
+ run_main(pp.main, ["s", "--workspace", self.ws.root])
+ md = read(os.path.join(self.adir, "VERIFICATION.md"))
+ self.assertNotRegex(md, r"[\x00\x1b]")
+ self.assertIn("Round \\| <img src=x onerror=1>", md)
+ self.assertNotIn("\n# heading", md)
+
+ def test_the_verdict_comes_from_the_evidence_not_from_an_earlier_pack(self):
+ run_main(pp.main, ["s", "--workspace", self.ws.root])
+ path = os.path.join(self.adir, "VERIFICATION.json")
+ data = load(path)
+ data["modules"][0]["verdict"] = "NOT PROVEN"
+ dump(path, data)
+ self.assertEqual(run_main(pp.main, ["s", "--workspace", self.ws.root])[0], 0)
+ self.assertEqual(load(path)["overall"]["verdict"], "PROVEN")
+
+ def test_a_huge_evidence_file_is_not_read(self):
+ put(self.ws.root, "analysis/s/equivalence/test-runs.json", b" " * (9 << 20), T0 + 40)
+ pack = self.ws.pack()
+ self.assertTrue(any("larger than 8 MB" in p for p in pack["problems"]))
+ self.assertEqual(pack["modules"][0]["verdict"], "NOT PROVEN")
+
+
+class ProofUplift(unittest.TestCase):
+ BASE = "# BASELINE\n\n## Per-test results\n\n| Test | Result |\n|---|---|\n| `T#a` | PASS |\n| `T#b` | PASS |\n| `T#c` | FAIL |\n| `T#d` | SKIP |\n"
+
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root, True)
+ put(self.root, "legacy/s/pom.xml", "<project/>", T0)
+ put(self.root, "analysis/s/PREFLIGHT.md", "x", T0 + 10)
+ put(self.root, "analysis/s/BASELINE.md", self.BASE, T0 + 10)
+ put(self.root, "modernized/s-uplifted/unit/src/Main.java", "class Main {}\n", T0 + 20)
+ put(self.root, "modernized/s-uplifted/UPLIFT_NOTES.md", "Canary: break a comparison -> 2 tests failed\n", T0 + 20)
+ put(self.root, "analysis/s/equivalence/canary/TEST-C.xml", junit([("T", "a", "FAIL", ""), ("T", "b", "FAIL", "")]), T0 + 35)
+ self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")])
+ put(self.root, "analysis/s/equivalence/test-runs.json", json.dumps({"legacy": {"ran": True}, "suites": [
+ {"module": "unit", "name": "unit", "junit": ["modernized/s-uplifted/unit/target/surefire-reports"], "executed": 3, "failed": 1, "skipped": 1}],
+ "canaries": [{"change": "break a comparison", "junit": ["analysis/s/equivalence/canary"]}]}), T0 + 40)
+ rows = []
+ for i in range(10):
+ put(self.root, "analysis/s/equivalence/fresh/old/%d.out" % i, "v%d\n" % i, T0 + 25)
+ put(self.root, "analysis/s/equivalence/fresh/new/%d.out" % i, "v%d\n" % i, T0 + 25)
+ rows.append({"id": "f%d" % i, "legacy": "fresh/old/%d.out" % i, "new": "fresh/new/%d.out" % i})
+ put(self.root, "analysis/s/equivalence/fresh-cases.json", json.dumps({"cases": rows}), T0 + 25)
+
+ def results(self, cases):
+ put(self.root, "modernized/s-uplifted/unit/target/surefire-reports/TEST-T.xml", junit(cases), T0 + 30)
+
+ def module(self):
+ pack = pp.overall(pp.build("s", self.root, now="x"))
+ self.assertEqual(len(pack["modules"]), 1)
+ return pack["modules"][0]
+
+ def test_no_regression_against_the_baseline_is_proven_and_traces_no_rules(self):
+ m = self.module()
+ self.assertEqual((m["verdict"], m["track"], m["name"]), ("PROVEN", "uplift", "s-uplifted"))
+ self.assertEqual({c["id"]: c["state"] for c in m["checks"]}["rules"], "na")
+ self.assertEqual(m["evidence"]["baseline"]["regressionsCount"], 0)
+
+ def test_a_regression_or_a_new_failure_is_not_proven(self):
+ self.results([("T", "a", "FAIL", ""), ("T", "b", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")])
+ m = self.module()
+ self.assertEqual(m["verdict"], "NOT PROVEN")
+ self.assertIn("1 test(s) passed before and fail now", m["reasons"][0])
+ self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", ""), ("T", "new", "FAIL", "")])
+ self.assertEqual(self.module()["verdict"], "NOT PROVEN")
+
+ def test_missing_tests_and_skipped_growth_are_partly_proven(self):
+ self.results([("T", "a", "PASS", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")])
+ m = self.module()
+ self.assertEqual(m["verdict"], "PARTLY PROVEN")
+ self.assertTrue(any("did not run now" in r for r in m["reasons"]))
+ self.results([("T", "a", "PASS", ""), ("T", "b", "SKIP", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")])
+ self.assertEqual(self.module()["verdict"], "PARTLY PROVEN")
+
+ def test_an_approved_baseline_difference_is_allowed_and_listed_as_a_decision(self):
+ put(self.root, "analysis/s/BASELINE.md", self.BASE + "\n## Approved differences\n\n| Test | Reason |\n|---|---|\n| `T#b` | the new runtime words the message differently |\n", T0 + 10)
+ self.results([("T", "a", "PASS", ""), ("T", "b", "FAIL", ""), ("T", "c", "FAIL", ""), ("T", "d", "SKIP", "")])
+ m = self.module()
+ self.assertEqual(m["verdict"], "PROVEN")
+ self.assertTrue(any("approved by a person in BASELINE.md" in c and "T#b" in c for c in m["caveats"]))
+ self.assertTrue(any("decision, not evidence" in n for n in m["notProven"]))
+ self.assertEqual(m["evidence"]["baseline"]["approved"][0]["id"], "T#b")
+
+ def test_a_canary_keyed_by_a_unit_of_the_uplifted_copy_is_accepted(self):
+ dump(os.path.join(self.root, "analysis", "s", "equivalence", "test-runs.json"), {"legacy": {"ran": True}, "suites": [
+ {"module": "unit", "name": "unit", "junit": ["modernized/s-uplifted/unit/target/surefire-reports"]}],
+ "canaries": [{"module": "unit", "change": "break a comparison", "junit": ["analysis/s/equivalence/canary"]}]})
+ m = self.module()
+ self.assertEqual({c["id"]: c["state"] for c in m["checks"]}["canary"], "pass")
+
+ def test_a_test_that_now_passes_needs_a_person_but_does_not_change_the_verdict(self):
+ self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "PASS", ""), ("T", "d", "SKIP", "")])
+ m = self.module()
+ self.assertEqual(m["verdict"], "PROVEN")
+ self.assertTrue(any("intended fix" in n for n in m["needsPerson"]))
+
+ def test_target_only_and_a_missing_baseline_cannot_be_proven(self):
+ self.results([("T", "a", "PASS", ""), ("T", "b", "PASS", ""), ("T", "c", "PASS", "")])
+ put(self.root, "analysis/s/BASELINE.md", "target-only: Java 8 is not installed here\n", T0 + 10)
+ m = self.module()
+ self.assertEqual(m["verdict"], "PARTLY PROVEN")
+ self.assertIn("target-only", " ".join(m["reasons"]))
+ self.assertFalse(m["evidence"]["legacy"]["ran"])
+ os.remove(os.path.join(self.root, "analysis", "s", "BASELINE.md"))
+ m = self.module()
+ self.assertEqual(m["verdict"], "PARTLY PROVEN")
+ self.assertIn("BASELINE.md is missing", " ".join(m["reasons"]))
+
+ def test_a_unit_argument_narrows_the_suites_and_an_unknown_name_is_an_error(self):
+ pack = pp.build("s", self.root, "unit", now="x")
+ self.assertEqual(pack["modules"][0]["name"], "s-uplifted")
+ self.assertEqual(pack["asked"], "unit")
+ with self.assertRaises(pp.InputError):
+ pp.build("s", self.root, "nosuchunit")
+
+
+# ---------------------------------------------------------------- the Proof section of the report
+def page_data(html):
+ return json.loads(re.search(r'<script type="application/json" id="report-data">(.*?)</script>', html, re.S).group(1))
+
+
+def good_pack(**module_change):
+ checks = [{"id": cid, "label": label, "state": "pass", "detail": "fine"} for cid, label in br.PROOF_CHECKS]
+ m = {"name": "mod", "track": "rewrite", "verdict": "PROVEN", "checks": checks, "verifiedAt": "2026-09-24 00:00 UTC",
+ "evidence": {"tests": {"executed": 5, "failed": 0, "skipped": 0},
+ "rules": {"p0": [{"id": "RULE-001", "name": "Total", "confidence": "High", "status": "tested", "tests": 3, "main": 1, "where": "src/test/A.java:9"}]},
+ "fresh": {"inputs": 12, "executed": 20, "same": 20, "differs": 0, "missing": 0}, "equivalence": {"cases": 4, "executed": 4, "same": 4, "differs": 0, "missing": 0, "approved": [], "masks": []}},
+ "notProven": ["It does not prove inputs nobody tried."], "brief": {"found": True, "items": [{"text": "A person accepts it", "where": "Phase 1 exit criterion"}], "count": 1}}
+ m.update(module_change)
+ return {"v": 1, "system": "s", "generated": "2026-09-24 00:00 UTC", "problems": [], "legacy": {"path": "legacy/s", "ran": True}, "modules": [m], "signoff": {}, "rules": ["PROVEN needs all six checks."]}
+
+
+class ProofReport(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root, True)
+ put(self.root, "analysis/s/PREFLIGHT.md", "# Preflight\n")
+ self.out = os.path.join(self.root, "out", "REPORT.html")
+
+ def report(self, pack):
+ put(self.root, "analysis/s/VERIFICATION.json", pack if isinstance(pack, (str, bytes)) else json.dumps(pack, indent=1)) # like proof_pack.py: short lines
+ code, _, err = run_main(br.main, ["s", "--workspace", self.root, "--out", self.out])
+ self.assertEqual(code, 0, err)
+ with open(self.out, encoding="utf-8") as fh:
+ return fh.read()
+
+ def proof(self, html):
+ data = page_data(html)
+ return data, next((p["proof"] for s in data["sections"] if s["id"] == "proof" for p in s["parts"] if p["t"] == "proof"), None)
+
+ def test_the_section_the_banner_and_the_order(self):
+ put(self.root, "analysis/s/EQUIVALENCE.json", "{}")
+ put(self.root, "modernized/s/mod/TRANSFORMATION_NOTES.md", "# n")
+ data, pv = self.proof(self.report(good_pack()))
+ self.assertEqual([s["id"] for s in data["sections"]][-3:], ["build", "proof", "equivalence"])
+ self.assertEqual((pv["verdict"], pv["counts"]["PROVEN"], pv["modules"][0]["p0Counts"]["tested"]), ("PROVEN", 1, 1))
+ self.assertEqual(data["glance"]["proof"]["verdict"], "PROVEN")
+ self.assertEqual(data["glance"]["proof"]["modules"], [{"name": "mod", "verdict": "PROVEN"}])
+ self.assertEqual(pv["signoff"], {"name": "", "role": "", "date": "", "decision": ""})
+ self.assertEqual(pv["modules"][0]["people"][0]["text"], "A person accepts it")
+
+ def test_no_pack_means_no_section_and_the_older_reports_are_unchanged(self):
+ code, _, _ = run_main(br.main, ["s", "--workspace", self.root, "--out", self.out])
+ data = page_data(read(self.out))
+ self.assertIsNone(data["glance"]["proof"])
+ self.assertNotIn("proof", [s["id"] for s in data["sections"]])
+
+ def test_the_verdict_is_recomputed_from_the_checks_never_taken_from_the_file(self):
+ pack = good_pack()
+ pack["modules"][0]["checks"][3]["state"] = "gap"
+ _, pv = self.proof(self.report(pack))
+ self.assertEqual(pv["modules"][0]["verdict"], "PARTLY PROVEN")
+ self.assertTrue(any("recorded PROVEN" in p and "PARTLY PROVEN" in p for p in pv["problems"]))
+ pack["modules"][0]["checks"][0]["state"] = "fail"
+ pack["modules"][0]["verdict"] = "PROVEN"
+ data, pv = self.proof(self.report(pack))
+ self.assertEqual((pv["verdict"], data["glance"]["proof"]["verdict"]), ("NOT PROVEN", "NOT PROVEN"))
+ self.assertEqual(pv["modules"][0]["reasons"][0], "Tests ran: fine")
+
+ def test_a_pack_that_contradicts_its_own_numbers_is_downgraded(self):
+ for change, check, want in (({"evidence": {"tests": {"executed": 3, "failed": 2}}}, 0, "fail"),
+ ({"evidence": {"tests": {"executed": 3}, "equivalence": {"differs": 1}, "fresh": {"inputs": 12}}}, 2, "fail"),
+ ({"evidence": {"tests": {"executed": 3}, "fresh": {"inputs": 12, "missing": 1}}}, 3, "fail"),
+ ({"evidence": {"tests": {"executed": 0}}}, 0, "fail"),
+ ({"evidence": {"tests": {"executed": 3}, "rules": {"p0": [{"id": "R", "status": "none"}]}}}, 1, "gap"),
+ ({"evidence": {"tests": {"executed": 3}, "fresh": {"inputs": 3}}}, 3, "gap"),
+ ({"evidence": {"tests": {"executed": 3}}}, 3, "gap")):
+ _, pv = self.proof(self.report(good_pack(**change)))
+ self.assertEqual(pv["modules"][0]["checks"][check]["state"], want, change)
+ self.assertNotEqual(pv["modules"][0]["verdict"], "PROVEN")
+ pack = good_pack()
+ pack["modules"][0]["checks"] = pack["modules"][0]["checks"][:5]
+ _, pv = self.proof(self.report(pack))
+ self.assertEqual(pv["modules"][0]["verdict"], "PARTLY PROVEN")
+ self.assertIn("missing from VERIFICATION.json", pv["modules"][0]["reasons"][0])
+ self.assertEqual(self.proof(self.report(dict(good_pack(), modules=[])))[1]["verdict"], "NOT PROVEN")
+
+ def test_a_real_pack_written_by_proof_pack_renders_the_same_verdict(self):
+ ws = Ws(self)
+ put(ws.root, "modernized/s/mod/src/test/CalcTest.java", "// RULE-001\n", T0 + 20)
+ run_main(pp.main, ["s", "--workspace", ws.root])
+ code, _, _ = run_main(br.main, ["s", "--workspace", ws.root])
+ data = page_data(read(os.path.join(ws.root, "analysis", "s", "REPORT.html")))
+ mod = data["glance"]["proof"]["modules"][0]
+ self.assertEqual(mod, {"name": "mod", "verdict": "PARTLY PROVEN"})
+ pv = next(p["proof"] for s in data["sections"] if s["id"] == "proof" for p in s["parts"])
+ self.assertEqual(pv["modules"][0]["p0Counts"], {"tested": 1, "claimedOnly": 0, "none": 1})
+ self.assertTrue(pv["modules"][0]["reasons"][0].startswith("Rules traced: 1 of 2 P0"))
+
+ def test_hostile_values_stay_data_and_the_page_keeps_its_rules(self):
+ evil = "<script>window.__pwned=1</script></script><img src=x onerror=1> &amp; " + chr(0x2028)
+ pack = good_pack(name=evil * 5, track=evil, notProven=[evil * 20] * 60, verdict=["PROVEN"], checks="nope",
+ evidence={"tests": {"executed": "many", "failed": -1, "skipped": 10 ** 30}, "rules": {"p0": [evil, {"id": evil, "status": evil, "tests": evil}] * 150},
+ "fresh": [1], "equivalence": {"approved": evil, "masks": [evil]}, "baseline": 5, "canary": [evil]},
+ brief={"items": [{"text": evil * 9, "where": evil}] * 100, "count": "x", "found": 1})
+ pack.update(problems=[evil] * 20, signoff="x", legacy=[], rules="x")
+ html = self.report(pack)
+ block = re.search(r'<script type="application/json" id="report-data">(.*?)</script>', html, re.S).group(1)
+ for bad in ("<", ">", "&", chr(0x2028)):
+ self.assertNotIn(bad, block)
+ data, pv = self.proof(html)
+ m = pv["modules"][0]
+ self.assertLessEqual(len(m["name"]), 120)
+ self.assertEqual((m["tests"], m["verdict"]), ({"executed": 0, "failed": 0, "skipped": 0}, "PARTLY PROVEN")) # no usable checks: nothing is proven
+ self.assertLessEqual(len(m["p0"]), 200)
+ self.assertLessEqual(len(m["people"]), 40)
+ self.assertLessEqual(len(pv["problems"]), 10 + 1)
+ self.assertEqual(html.count("<script"), 2)
+ self.assertNotRegex(html.replace(block, "").split('<script id="app">')[0].split("</style>")[1], r"__pwned|onerror=")
+ policy = re.search(r'http-equiv="Content-Security-Policy" content="([^"]*)"', html).group(1)
+ self.assertIn("default-src 'none'", policy)
+
+ def test_malformed_or_foreign_verification_files_are_reported_not_raised(self):
+ for text in ("[1, 2", "{}", '{"modules": "x"}', "[]", "null", b"\x00\x01"):
+ data = page_data(self.report(text))
+ self.assertEqual(data["glance"]["proof"]["verdict"], "NOT PROVEN" if text != "[1, 2" else "NOT PROVEN", text)
+ html = self.report("[1, 2")
+ self.assertTrue(any("VERIFICATION.json could not be parsed" in json.dumps(p) for s in page_data(html)["sections"] for p in s["parts"]))
+
+ def test_a_linked_verification_file_is_not_read(self):
+ outside = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, outside, True)
+ put(outside, "V.json", json.dumps(good_pack()))
+ make_symlink(self, os.path.join(outside, "V.json"), os.path.join(self.root, "analysis", "s", "VERIFICATION.json"))
+ code, _, _ = run_main(br.main, ["s", "--workspace", self.root, "--out", self.out])
+ data = page_data(read(self.out))
+ self.assertIsNone(data["glance"]["proof"])
+
+
+NODE_PROOF = r"""
+const fs = require('fs'), vm = require('vm');
+const tpl = fs.readFileSync(process.env.TEMPLATE, 'utf8');
+const grab = function (re) { return re.exec(tpl)[1] !== undefined ? re.exec(tpl)[1] : re.exec(tpl)[0]; };
+const core = /\/\* core:start[^\n]*\n([\s\S]*?)\/\* core:end \*\//.exec(tpl)[1];
+const proof = /\/\* proof:start[^\n]*\n([\s\S]*?)\/\* proof:end \*\//.exec(tpl)[1];
+const helpers = /function fmt\(n\)[^\n]*\n/.exec(tpl)[0] + /function chip\([^\n]*\n/.exec(tpl)[0];
+class Text { constructor(t) { this.text = String(t); } }
+class El { constructor(t) { this.tag = t; this.attrs = {}; this.kids = []; }
+ setAttribute(k, v) { this.attrs[k] = String(v); } appendChild(c) { this.kids.push(c); return c; } }
+const ctx = { document: { createElement: t => new El(t), createTextNode: t => new Text(t) } };
+vm.createContext(ctx);
+const api = vm.runInContext('(function(){"use strict";' + core + helpers + proof + ';return {partProof:partProof,own:own};})()', ctx);
+function walk(n, acc, top) {
+ if (n instanceof Text) { acc.text += n.text + '\n'; return; }
+ acc.tags.add(n.tag); Object.keys(n.attrs).forEach(k => { acc.attrs.add(k); });
+ if (top && n.tag === 'div' && /banner/.test(n.attrs.class || '')) acc.banners.push(n.attrs.class);
+ n.kids.forEach(c => walk(c, acc, false));
+}
+const input = JSON.parse(fs.readFileSync(0, 'utf8')), out = [];
+for (const pv of input) {
+ const t0 = Date.now(), acc = { tags: new Set(), attrs: new Set(), text: '', banners: [] };
+ api.partProof(pv).forEach(n => walk(n, acc, true));
+ out.push({ ms: Date.now() - t0, tags: [...acc.tags], attrs: [...acc.attrs], text: acc.text, banners: acc.banners });
+}
+out.push({ own: [api.own({a: 'x'}, 'a', 'd'), api.own({a: 'x'}, '__proto__', 'd'), api.own({a: 'x'}, 'constructor', 'd'), api.own({a: 'x'}, 'toString', 'd')] });
+process.stdout.write(JSON.stringify(out));
+"""
+
+
+@unittest.skipUnless(NODE, "node is not installed")
+class ProofScript(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ evil = "<script>alert(1)</script></script><img src=x onerror=alert(2)> [x](javascript:alert(3))"
+ packs = [good_pack(),
+ good_pack(checks=[{"id": "tests", "label": "Tests ran", "state": "gap", "detail": "x"}]),
+ good_pack(checks=[{"id": "tests", "label": "Tests ran", "state": "fail", "detail": "x"}]),
+ good_pack(name=evil, track=evil, notProven=[evil], brief={"found": True, "count": 900, "items": [{"text": evil, "where": evil}]},
+ evidence={"tests": {"executed": 1}, "rules": {"p0": [{"id": evil, "name": evil, "status": "__proto__", "tests": 1, "main": 1, "where": evil}] * 200}}),
+ dict(good_pack(), legacy={"path": evil, "target": evil, "ran": False}, problems=[evil], signoff={"name": evil, "role": "", "date": "", "decision": ""})]
+ views = [br.proof_view(p) for p in packs]
+ views[3]["verdict"] = "__proto__"
+ views[3]["modules"][0]["verdict"] = "constructor"
+ proc = subprocess.run([NODE, "-e", NODE_PROOF], input=json.dumps(views), capture_output=True, text=True, env=dict(os.environ, TEMPLATE=TEMPLATE), timeout=120)
+ assert proc.returncode == 0, proc.stderr
+ cls.out, cls.evil = json.loads(proc.stdout), evil
+
+ def test_only_safe_elements_and_attributes_are_built(self):
+ allowed_tags = {"div", "table", "thead", "tbody", "tr", "th", "td", "span", "p", "h3", "h4", "ul", "li", "details", "summary"}
+ allowed_attrs = {"class", "role", "tabindex", "aria-label", "scope"}
+ for doc in self.out[:-1]:
+ self.assertLessEqual(set(doc["tags"]), allowed_tags)
+ self.assertLessEqual(set(doc["attrs"]), allowed_attrs)
+ self.assertLess(doc["ms"], 3000)
+
+ def test_hostile_text_is_shown_as_text_never_as_markup_or_a_link(self):
+ doc = self.out[3]
+ self.assertIn("<script>alert(1)</script>", doc["text"])
+ self.assertIn("[x](javascript:alert(3))", doc["text"])
+ self.assertNotIn("a", doc["tags"])
+ self.assertNotIn("img", doc["tags"])
+
+ def test_the_banner_says_the_verdict_in_words_symbols_and_colour(self):
+ self.assertIn("✓ Proof: 1 PROVEN", self.out[0]["text"])
+ self.assertEqual(self.out[0]["banners"], ["banner ok", "banner ok"])
+ self.assertEqual(self.out[1]["banners"], ["banner warn", "banner warn"])
+ self.assertEqual(self.out[2]["banners"], ["banner bad", "banner bad"])
+ self.assertIn("◐ ", self.out[1]["text"])
+ self.assertIn("✗ ", self.out[2]["text"])
+
+ def test_unknown_verdicts_and_prototype_names_fall_back_to_red(self):
+ self.assertEqual(self.out[3]["banners"], ["banner bad", "banner bad"])
+ self.assertEqual(self.out[-1]["own"], ["x", "d", "d", "d"])
+
+ def test_the_page_shows_the_matrix_what_is_not_proven_and_a_blank_sign_off(self):
+ text = self.out[0]["text"]
+ for needle in ("What this does not prove", "It does not prove inputs nobody tried.", "P0 business rules: 1 tested, 0 claimed only, 0 with no test", "RULE-001",
+ "Waiting for a person", "A person accepts it", "Sign-off", "________________", "accept / accept with conditions / reject", "How the verdict is computed",
+ "Fresh inputs: 12 new input(s)", "tests executed: 5"):
+ self.assertIn(needle, text)
+ self.assertIn("It could not run here, so the proof is trace-based.", self.out[4]["text"])
+
+ def test_the_template_keeps_its_own_contract(self):
+ with open(TEMPLATE, encoding="utf-8") as fh:
+ text = fh.read()
+ app = re.search(r'<script id="app">(.*?)</script>', text, re.S).group(1)
+ self.assertEqual(len(re.findall(r"/\* proof:start", app)), 1)
+ self.assertNotRegex(app, r"innerHTML|outerHTML|insertAdjacentHTML|document\.write|eval\(|new Function|fetch\(|XMLHttpRequest")
+ self.assertNotRegex(text, r"https?://")
+ self.assertIn("case 'proof': return partProof(p.proof);", app)
diff --git a/plugins/code-modernization/scripts/trace_rules.py b/plugins/code-modernization/scripts/trace_rules.py
new file mode 100644
index 00000000..5d9d4691
--- /dev/null
+++ b/plugins/code-modernization/scripts/trace_rules.py
@@ -0,0 +1,391 @@
+#!/usr/bin/env python3
+"""Trace every business rule to the code and the tests that name it.
+
+ python3 trace_rules.py <system> [--workspace DIR] [--json] [--all]
+
+Reads analysis/<system>/BUSINESS_RULES.md (rule cards: "### RULE-NNN: name" with **Priority:**,
+**Confidence:** and **Source:** lines), then scans the built code under modernized/<system>,
+modernized/<system>-uplifted and modernized/<system>-reimagined (never build output: target/,
+build/, dist/, node_modules/, bin/, obj/, __pycache__/, or any folder starting with a dot) for
+mentions of each rule id, and sorts every file into "test" or "main" code. One row per rule.
+
+Evidence, strongest first:
+ tested a test file names the rule
+ code only only main code names it
+ claimed only only the mapping table in TRANSFORMATION_NOTES.md or UPLIFT_NOTES.md names it, on a
+ row that also names a file that exists in the module
+ none nothing names it
+
+A mention is RULE-017 (any case, or RULE_017), rule017 or Rule017 inside an identifier such as
+rule017_emptyInput or testRule017, and the shorthand RULE-002/003 and RULE-001, -018. Nothing is
+guessed from words: a rule that no file names by id is not "tested", however well its behavior may
+be covered. A mention shows that a test names the rule, not that the test is good.
+
+A test is a file under a folder called test, tests, __tests__, spec or specs, or named like
+FooTest.java, FooTests.cs, TestFoo.java, test_foo.py, foo_test.go, foo.spec.ts or foo.test.js.
+Documentation files (.md, .txt, .rst, .adoc) are never code. Symbolic links are never followed.
+Everything read is untrusted text: it is never executed and only shortened, never trusted.
+
+Exit 0 when every P0 rule has a test that names it, 1 when some do not, 2 when the rules file
+cannot be read. Standard library only.
+"""
+import argparse
+import collections
+import json
+import os
+import re
+import sys
+
+SKIP_DIRS = {"target", "build", "dist", "node_modules", "bin", "obj", "__pycache__", "venv"}
+DOC_EXT = {".md", ".markdown", ".rst", ".txt", ".adoc"}
+TEST_DIRS = {"test", "tests", "__tests__", "spec", "specs"}
+TEST_NAME = re.compile(r"^test_|_tests?\.[^.]+$|\.(?:spec|test)\.[^.]+$|(?:Test|Tests|TestCase|IT)\.[^.]+$|^Test[A-Z0-9_]")
+NOTES_NAMES = ("TRANSFORMATION_NOTES.md", "UPLIFT_NOTES.md")
+TRACKS = (("rewrite", ""), ("uplift", "-uplifted"), ("reimagine", "-reimagined"))
+FILE_CAP, RULES_CAP, NOTES_CAP, LINE_CAP, MAX_FILES, SAMPLES = 2 << 20, 8 << 20, 1 << 20, 4000, 200000, 3
+MENTION = [re.compile(r"(?<![A-Za-z0-9])rule[-_](\d{1,6})(?!\d)", re.I),
+ re.compile(r"(?<![A-Za-z0-9])rule(\d{3,6})(?!\d)", re.I),
+ re.compile(r"(?<=[a-z])Rule[-_]?(\d{3,6})(?!\d)")]
+MORE = re.compile(r"(?:/|,[ \t]*-)(\d{2,6})(?!\d)")
+NOT_A_CLAIM = re.compile(r"(?i)not migrated|not implemented|not ported|removed|retired|dead code|dropped|out of scope")
+CARD = re.compile(r"#{2,5}[ \t]+[*`\[]*RULE[-_](\d{1,6})(?![A-Za-z0-9])", re.I)
+FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
+PATH = re.compile(r"[A-Za-z0-9_@][A-Za-z0-9_@./+-]{0,199}\.[A-Za-z][A-Za-z0-9]{0,7}(?![A-Za-z0-9_])")
+
+
+def clean(value, limit=200):
+ text = " ".join(re.sub(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]", " ", str(value if value is not None else "")).split())
+ return text if len(text) <= limit else text[:limit - 1] + "\u2026"
+
+
+def read_text(path, cap):
+ """Text of a regular, non-binary file (first `cap` bytes), or None."""
+ try:
+ with open(path, "rb") as fh:
+ raw = fh.read(cap)
+ except OSError:
+ return None
+ return None if b"\x00" in raw[:4096] else raw.decode("utf-8", "replace")
+
+
+def find_ids(text):
+ """[(rule number, offset)] for every id named in text, shorthand included."""
+ found = []
+ for rx in MENTION:
+ for m in rx.finditer(text):
+ found.append((int(m.group(1)), m.start()))
+ pos = m.end()
+ more = MORE.match(text, pos)
+ while more:
+ found.append((int(more.group(1)), m.start()))
+ pos = more.end()
+ more = MORE.match(text, pos)
+ return found
+
+
+def field(lines, name):
+ """The value of a "**Name:** value" line, or ''. Linear in the line length whatever the line holds."""
+ for line in lines:
+ s = line[:LINE_CAP].lstrip(" \t>*-")
+ if s[:len(name)].lower() == name.lower():
+ rest = s[len(name):].lstrip("*").lstrip(" \t")
+ if rest.startswith(":"):
+ return rest[1:].lstrip(" \t*").strip()
+ return ""
+
+
+def parse_rules(text):
+ """-> ([rule dicts in file order], [notes]). A duplicate id keeps its first card."""
+ rules, notes, seen, card, fence, rows = [], [], set(), None, "", {}
+ lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
+ for line in lines:
+ if line.lstrip().startswith("|"):
+ cells = [re.sub(r"[*`]", "", c).strip() for c in line[:LINE_CAP].strip().strip("|").split("|")]
+ ids = [int(m.group(1)) for c in cells for m in [re.fullmatch(r"RULE[-_](\d{1,6})", c, re.I)] if m]
+ if ids:
+ rows.setdefault(ids[0], {"p": next((c for c in cells if re.fullmatch(r"P\d", c)), ""),
+ "c": next((c for c in cells if re.match(r"(?i)(high|medium|low)\b", c)), "")})
+ for line in lines:
+ f = FENCE.match(line)
+ if fence:
+ fence = "" if f and f.group(1)[0] == fence[0] and len(f.group(1)) >= len(fence) else fence
+ if card is not None:
+ card["body"].append(line)
+ continue
+ if f:
+ fence = f.group(1)
+ m = None if f else CARD.match(line[:LINE_CAP])
+ if not f and re.match(r"#{1,6}\s", line):
+ card = None
+ if m:
+ n = int(m.group(1))
+ if n in seen:
+ notes.append("RULE-%03d has more than one card; the first was used." % n)
+ continue
+ seen.add(n)
+ name = line[m.end():LINE_CAP].lstrip("*`] \t:\u00b7\u2013\u2014-").rstrip("# \t")
+ card = {"n": n, "id": "RULE-%03d" % n, "name": clean(name, 160), "body": []}
+ rules.append(card)
+ elif card is not None:
+ card["body"].append(line)
+ for r in rules:
+ body = r.pop("body")
+ prio = re.search(r"\bP\d\b", field(body, "Priority"))
+ conf = re.search(r"(?i)\b(high|medium|low)\b", field(body, "Confidence"))
+ row = rows.get(r["n"], {})
+ source = field(body, "Source")
+ first = PATH.search(source)
+ r.update({"priority": prio.group(0) if prio else row.get("p", ""),
+ "confidence": conf.group(1).capitalize() if conf else row.get("c", "").capitalize()[:10],
+ "source": clean(source, 160), "sourceFile": os.path.basename(first.group(0)) if first else ""})
+ return rules, notes
+
+
+def file_kind(rel):
+ parts = rel.split("/")
+ name = parts[-1]
+ if os.path.splitext(name)[1].lower() in DOC_EXT:
+ return "doc"
+ if any(p.lower() in TEST_DIRS for p in parts[:-1]) or TEST_NAME.search(name):
+ return "test"
+ return "main"
+
+
+def is_real_dir(path):
+ return os.path.isdir(path) and not os.path.islink(path)
+
+
+def discover_modules(workspace, system):
+ """[{name, track, path, rel}] for every built module under modernized/."""
+ out = []
+ for track, suffix in TRACKS:
+ root = os.path.join(workspace, "modernized", system + suffix)
+ if not is_real_dir(root):
+ continue
+ rel = "modernized/" + system + suffix
+ if track == "uplift":
+ out.append({"name": system + suffix, "track": track, "path": root, "rel": rel})
+ continue
+ try:
+ subs = sorted(d for d in os.listdir(root) if not d.startswith(".") and d not in SKIP_DIRS and is_real_dir(os.path.join(root, d)))
+ except OSError:
+ subs = []
+ for d in subs:
+ out.append({"name": d, "track": track, "path": os.path.join(root, d), "rel": rel + "/" + d})
+ if not subs:
+ out.append({"name": system + suffix, "track": track, "path": root, "rel": rel})
+ return out
+
+
+def walk_module(path, budget):
+ """([(relative posix path, absolute path)] of regular files, links skipped, cut short)."""
+ files, skipped = [], 0
+ for base, dirs, names in os.walk(path):
+ keep = []
+ for d in sorted(dirs):
+ if d.startswith(".") or d in SKIP_DIRS:
+ continue
+ if os.path.islink(os.path.join(base, d)):
+ skipped += 1
+ continue
+ keep.append(d)
+ dirs[:] = keep
+ for n in sorted(names):
+ full = os.path.join(base, n)
+ if os.path.islink(full):
+ skipped += 1
+ elif not n.startswith(".") and os.path.isfile(full):
+ if len(files) >= budget:
+ return files, skipped, True
+ files.append((os.path.relpath(full, path).replace(os.sep, "/"), full))
+ return files, skipped, False
+
+
+def claims_of(notes, names):
+ """(rule numbers claimed, rule rows naming no existing file, basenames of every file the notes name).
+ A row claims a rule only when it names the rule AND a file that exists in the module."""
+ claimed, unresolved, named, head = set(), 0, set(), ""
+ for line in notes.split("\n"):
+ line = line[:LINE_CAP]
+ tokens = PATH.findall(line)
+ named.update(os.path.basename(t) for t in tokens)
+ if line.startswith("#"):
+ head = line.lstrip("#").strip()
+ if not line.lstrip().startswith("|") or NOT_A_CLAIM.search(head): # a table under "Not migrated" claims nothing
+ continue
+ ids = {n for n, _ in find_ids(line)}
+ if not ids:
+ continue
+ if any(os.path.basename(t) in names and any(p == t or p.endswith("/" + t) for p in names[os.path.basename(t)]) for t in tokens):
+ claimed |= ids
+ else:
+ unresolved += 1
+ return claimed, unresolved, named
+
+
+def status_of(main, tests, claimed):
+ return "tested" if tests else "code only" if main else "claimed only" if claimed else "none"
+
+
+def blank():
+ return {"main": 0, "tests": 0, "claimed": False, "named": False}
+
+
+def trace(workspace, system):
+ """-> the trace. Raises OSError when BUSINESS_RULES.md cannot be read."""
+ rules_path = os.path.join(workspace, "analysis", system, "BUSINESS_RULES.md")
+ if os.path.islink(rules_path):
+ raise OSError("analysis/%s/BUSINESS_RULES.md is a symbolic link" % system)
+ text = read_text(rules_path, RULES_CAP)
+ if text is None:
+ raise OSError("analysis/%s/BUSINESS_RULES.md is missing or is not text" % system)
+ rules, notes = parse_rules(text)
+ by_n = {r["n"]: r for r in rules}
+ per = {r["n"]: {} for r in rules}
+ samples = {r["n"]: {"main": [], "tests": []} for r in rules}
+ modules, budget = [], MAX_FILES
+ scan = {"files": 0, "textFiles": 0, "linksSkipped": 0, "cut": False}
+ for mod in discover_modules(workspace, system):
+ files, skipped, cut = walk_module(mod["path"], budget)
+ budget -= len(files)
+ names = collections.defaultdict(list)
+ for rel, _ in files:
+ names[os.path.basename(rel)].append(rel)
+ notes_name = next((n for n in NOTES_NAMES if n in names[n]), "")
+ claimed, unresolved, named = set(), 0, set()
+ if notes_name:
+ ntext = read_text(os.path.join(mod["path"], notes_name), NOTES_CAP)
+ if ntext is not None:
+ claimed, unresolved, named = claims_of(ntext, names)
+ test_files = 0
+ for rel, full in files:
+ kind = file_kind(rel)
+ if kind == "doc":
+ continue
+ key = "tests" if kind == "test" else "main"
+ test_files += kind == "test"
+ body = read_text(full, FILE_CAP)
+ scan["textFiles"] += body is not None
+ hits = [(n, None) for n, _ in find_ids(os.path.basename(rel))] + [(n, at) for n, at in find_ids(body or "")]
+ for n, at in hits:
+ if n not in by_n:
+ continue
+ per[n].setdefault(mod["rel"], blank())[key] += 1
+ place = "%s/%s" % (mod["rel"], rel)
+ if len(samples[n][key]) < SAMPLES and not any(s.rsplit(":", 1)[0] == place for s in samples[n][key]):
+ samples[n][key].append("%s:%d" % (place, 0 if at is None else body.count("\n", 0, at) + 1))
+ for n in claimed & set(by_n):
+ per[n].setdefault(mod["rel"], blank())["claimed"] = True
+ for r in rules:
+ if r["sourceFile"] and r["sourceFile"] in named:
+ per[r["n"]].setdefault(mod["rel"], blank())["named"] = True
+ scan["files"] += len(files)
+ scan["linksSkipped"] += skipped
+ scan["cut"] = scan["cut"] or cut
+ modules.append({"name": mod["name"], "track": mod["track"], "path": mod["rel"], "files": len(files), "testFiles": test_files,
+ "notes": notes_name, "claimRowsUnresolved": unresolved})
+ out = []
+ for r in rules:
+ slots = per[r["n"]]
+ main, tests_n = sum(s["main"] for s in slots.values()), sum(s["tests"] for s in slots.values())
+ claim = any(s["claimed"] for s in slots.values())
+ out.append({"id": r["id"], "name": r["name"], "priority": r["priority"], "confidence": r["confidence"], "source": r["source"],
+ "main": main, "tests": tests_n, "claimed": claim, "status": status_of(main, tests_n, claim),
+ "perModule": slots, "samples": samples[r["n"]]})
+ if scan["cut"]:
+ notes.append("More than %d files were found, so the scan stopped early." % MAX_FILES)
+ if scan["linksSkipped"]:
+ notes.append("%d symbolic link(s) were not followed." % scan["linksSkipped"])
+ if not modules:
+ notes.append("No built code was found under modernized/%s, %s-uplifted or %s-reimagined." % (system, system, system))
+ return {"system": clean(system, 100), "rulesFile": "analysis/%s/BUSINESS_RULES.md" % system, "modules": modules, "rules": out,
+ "totals": totals(out), "p0NoTests": [r["id"] for r in out if r["priority"] == "P0" and r["status"] != "tested"],
+ "scan": scan, "notes": notes}
+
+
+def totals(rows):
+ """Per priority: rules, and how many are tested / code only / claimed only / none."""
+ out = {}
+ for r in rows:
+ t = out.setdefault(r["priority"] or "unrated", {"rules": 0, "tested": 0, "code only": 0, "claimed only": 0, "none": 0})
+ t["rules"] += 1
+ t[r["status"]] += 1
+ return dict(sorted(out.items()))
+
+
+def module_view(result, rel):
+ """The rules one module answers for, each with the module's own status. A rewrite answers for the rules its code,
+ tests or notes name, or whose legacy file its notes name; an uplift keeps the whole code, so it answers for all.
+ When nothing ties any rule to the module, every rule counts (`tied` is then False): an empty list must never pass."""
+ mod = next((m for m in result["modules"] if m["path"] == rel), None)
+ rows, tied = [], True
+ for r in result["rules"]:
+ slot = r["perModule"].get(rel) or blank()
+ if mod and (mod["track"] == "uplift" or slot["main"] or slot["tests"] or slot["claimed"] or slot["named"]):
+ rows.append(dict(r, main=slot["main"], tests=slot["tests"], claimed=slot["claimed"], status=status_of(slot["main"], slot["tests"], slot["claimed"])))
+ if mod and not rows and result["rules"]:
+ tied = False
+ for r in result["rules"]:
+ slot = r["perModule"].get(rel) or blank()
+ rows.append(dict(r, main=slot["main"], tests=slot["tests"], claimed=slot["claimed"], status=status_of(slot["main"], slot["tests"], slot["claimed"])))
+ return {"rows": rows, "totals": totals(rows), "outOfScope": len(result["rules"]) - len(rows), "tied": tied,
+ "p0NoTests": [r["id"] for r in rows if r["priority"] == "P0" and r["status"] != "tested"]}
+
+
+def render(result, everything=False, view=None, module=None):
+ """The matrix as text. With `view` (from module_view) only the rules that module answers for are listed."""
+ rows = view["rows"] if view else result["rules"]
+ tot = view["totals"] if view else result["totals"]
+ missing = view["p0NoTests"] if view else result["p0NoTests"]
+ scanned = ", ".join("%s (%d files, %d test)" % (clean(m["name"], 60), m["files"], m["testFiles"]) for m in result["modules"]
+ if not module or m["name"] == module) or "nothing built yet"
+ head = "Rule trace for %s%s: %d rule(s) in %s" % (result["system"], ", module " + clean(module, 60) if module else "", len(result["rules"]), result["rulesFile"])
+ lines = [head, "Scanned: " + scanned]
+ if view:
+ lines.append("Counted for this module: %d rule(s)%s" % (len(rows), "" if view["tied"] else " (nothing ties a rule to it by name, so every rule counts)"))
+ lines.append("")
+ for p, c in tot.items():
+ lines.append("%-7s %3d rules: %d tested, %d code only, %d claimed only, %d none" % (p, c["rules"], c["tested"], c["code only"], c["claimed only"], c["none"]))
+ lines += ["", "%-9s %-4s %-7s %5s %5s %s" % ("Rule", "Pri", "Conf", "Code", "Tests", "Status")]
+ shown = [r for r in rows if everything or r["priority"] == "P0"] + ([] if everything else [r for r in rows if r["priority"] != "P0"][:40])
+ for r in shown:
+ lines.append("%-9s %-4s %-7s %5d %5d %s %s" % (r["id"], r["priority"] or "-", r["confidence"] or "-", r["main"], r["tests"], r["status"], clean(r["name"], 60)))
+ if len(shown) < len(rows):
+ lines.append("... %d more rule(s) not listed (use --all)" % (len(rows) - len(shown)))
+ lines += ["", "P0 rules with no test that names them: " + (", ".join(missing) if missing else "none")]
+ lines += ["Note: " + n for n in result["notes"]]
+ return "\n".join(lines)
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description="Trace business rules to the code and tests that name them.")
+ ap.add_argument("system", help="the system's folder name under analysis/")
+ ap.add_argument("--workspace", default=".", help="the project root holding analysis/ and modernized/ (default: current folder)")
+ ap.add_argument("--json", action="store_true", help="print the full trace as JSON")
+ ap.add_argument("--all", action="store_true", help="list every rule, not just P0 and the first 40 others")
+ ap.add_argument("--module", metavar="NAME", help="only the rules this built module answers for (a folder under modernized/<system>/)")
+ args = ap.parse_args(argv)
+ if not args.system or args.system in (".", "..") or re.search(r"[\\/\x00]", args.system):
+ print("trace_rules.py: the system must be a folder name under analysis/, not a path", file=sys.stderr)
+ return 2
+ try:
+ result = trace(args.workspace, args.system)
+ except OSError as err:
+ print("trace_rules.py: %s" % err, file=sys.stderr)
+ return 2
+ view, mod = None, None
+ if args.module:
+ mod = next((m for m in result["modules"] if m["name"].lower() == args.module.lower()), None)
+ if mod is None:
+ print("trace_rules.py: no built module called %s (found: %s)" % (clean(args.module, 60), ", ".join(clean(m["name"], 40) for m in result["modules"]) or "none"), file=sys.stderr)
+ return 2
+ view = module_view(result, mod["path"])
+ if args.json:
+ print(json.dumps(dict(result, moduleView=view) if view else result, indent=1, ensure_ascii=True))
+ else:
+ print(render(result, args.all, view, mod["name"] if mod else None))
+ return 1 if (view["p0NoTests"] if view else result["p0NoTests"]) else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())