Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ The owner's direction (26 November 2026): make Reframe credible to someone readi
| Q1-03 | Types in CI | [CONTRIBUTING](../CONTRIBUTING.md) | #452 · Done 26 November 2026 (#455): `mypy` passes in CI. The modules with type errors still to fix are listed in `pyproject.toml`, and the list only shrinks: 25 of 85 modules at the start, after 13 were fixed |
| Q1-04 | Tests of the drivers, and a coverage floor | [CONTRIBUTING](../CONTRIBUTING.md) | #453 · Done 26 November 2026 (#455): The Claude assessment's driver, the AWS Transform assessment's driver and the command handlers are tested stage by stage with fakes, and CI fails below 80% line coverage. At the start: 81% overall; the drivers went from 44%, 38% and 46% to 95%, 93% and 71% |
| Q1-05 | Split `core/commands.py` | – | #454 · **Next:** unblocked now that v1.0.0 is tagged (27 November 2026). The 900-line module becomes one module per command group, with the Q1-04 tests passing unchanged |
| Q1-06 | Types in every module | [CONTRIBUTING](../CONTRIBUTING.md) | #483 · Done 27 November 2026 (#484): `mypy` passes in CI with every module checked except `reframe.core.commands`, which comes off the list once Q1-05 has split it. The 24 other modules on the list (108 errors at the start) are fixed without changing what the code does, and the offline tests pass unchanged; any real fault the types turn up is fixed with a test and listed in the PR. Two were: preflight accepted a sign-in that named no account, and the reports store could return no bucket |

## Release 1.1: any legacy codebase

Expand Down
31 changes: 3 additions & 28 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,33 +74,8 @@ ignore_missing_imports = true
warn_unused_ignores = true
warn_redundant_casts = true

# Modules with type errors still to fix (Q1-03). The list only shrinks: take a module off once it is clean.
# Modules with type errors still to fix (Q1-03, Q1-06). The list only shrinks: take a module off once it is clean.
# `reframe.core.commands` comes off once Q1-05 has split it.
[[tool.mypy.overrides]]
module = [
"reframe.claude.graph",
"reframe.claude.load",
"reframe.claude.runner",
"reframe.claude.steps",
"reframe.core.commands",
"reframe.core.pipeline",
"reframe.core.teardown",
"reframe.design.flow",
"reframe.design.inventory",
"reframe.design.journeys",
"reframe.design.package",
"reframe.infrastructure.network",
"reframe.reconcile.audit",
"reframe.reconcile.decide",
"reframe.reconcile.inputs",
"reframe.reconcile.questions",
"reframe.reconcile.requirements",
"reframe.report.build",
"reframe.report.compare",
"reframe.report.store",
"reframe.source.s3",
"reframe.transform.answers",
"reframe.transform.api",
"reframe.transform.documents",
"reframe.transform.retrieve",
]
module = ["reframe.core.commands"]
ignore_errors = true
5 changes: 3 additions & 2 deletions src/reframe/claude/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ def _literal(value: Any) -> str:

class Quads:
def __init__(self, run: str) -> None:
self.run, self.graph, self.lines = run, graph_iri(run), []
self.run, self.graph = run, graph_iri(run)
self.lines: list[str] = []

def iri(self, kind: str, ident: str) -> str:
return f"urn:reframe:claude:{self.run}:{kind}:{_local(ident)}"

def add(self, subject: str, predicate: str, obj: str, literal: bool = True) -> None:
def add(self, subject: str, predicate: str, obj: Any, literal: bool = True) -> None:
if obj is None or obj == "":
return
o = _literal(obj) if literal else f"<{obj}>"
Expand Down
1 change: 1 addition & 0 deletions src/reframe/claude/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ def graph(ctx: Context, model: dict[str, Any], generated: dict[str, Any]) -> dic
return update(ctx, graph={"skipped": iso(), "reason": reason, "file": "outputs/claude/graph.nq"})["graph"]
digest = hashlib.sha256(path.read_bytes()).hexdigest()
fn = loader(ctx, create=True)
assert fn is not None # with create, loader returns the loader or stops
outputs = ctx.changes.receipt("terraform-project-apply-graph-loader")["outputs"]
bucket, key = outputs["bucket"], KEY.format(run=run)

Expand Down
2 changes: 1 addition & 1 deletion src/reframe/claude/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def summarize(name: str, lines: list[dict[str, Any]], seconds: float, returncode
results = [line for line in lines if line.get("type") == "result"]
if not results:
tail = " ".join(str(line)[:200] for line in lines[-3:])
problem = "signin" if any(w in tail.casefold() for w in SIGNIN_WORDS) else "limit" if any(w in tail.casefold() for w in LIMIT_WORDS) else "failed"
problem: str | None = "signin" if any(w in tail.casefold() for w in SIGNIN_WORDS) else "limit" if any(w in tail.casefold() for w in LIMIT_WORDS) else "failed"
return StepResult(name, False, text=f"no result (exit {returncode}) {tail}", session_id=session, seconds=seconds, problem=problem)
# Claude Code can end with an empty "success" result for a background task's notice, after the step's real result
# (found on the second test codebase, 26 November 2026: the real one was the usage limit). That notice is not the step's answer.
Expand Down
7 changes: 6 additions & 1 deletion src/reframe/claude/steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,12 @@ def run_step(folder: RunFolder, claude: ClaudeCode, analysis: Path, step: str, p
folder.event("claude_step", step=step, attempt=attempt, resume=bool(resume), follow_up=follow_up)
_save(folder, step, {"ok": False, "attempt": attempt, "started_at": iso(), "session_id": (done or {}).get("session_id"),
"follow_ups": (done or {}).get("follow_ups", 0) + (1 if follow_up else 0)})
text = follow_up_prompt(system) if follow_up else resume_prompt if resume else prompt
if follow_up and system: # follow_up needs system
text = follow_up_prompt(system)
elif resume and resume_prompt: # resume needs resume_prompt
text = resume_prompt
else:
text = prompt
result = claude.run(f"{step}-{attempt}", text, timeout=STEP_HOURS.get(step, 2) * 3600, resume=None if follow_up else resume)
expected = analysis / EXPECTED[step]
if result.ok and not expected.exists():
Expand Down
1 change: 1 addition & 0 deletions src/reframe/core/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def prepare(ctx: Context, prompt: Callable[[str], str] | None, say: Callable[[st
transform_ready=lambda: client.call("list_resources", {"resource": "workspaces"}))
ctx.folder.save("preflight.json", report.as_json())
preflight.require(report)
assert report.account # preflight.require refuses a sign-in that names no account
ctx.folder.update(account=report.account, terraform_version=report.terraform)
if ctx.state.get("graph") is None:
names = ctx.names()
Expand Down
2 changes: 2 additions & 0 deletions src/reframe/core/preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ def check(*, aws: Aws, terraform: str, source: str, ref: str | None, transform_r
report.problems.append(f"{tool} is not on PATH: {fix}")
try:
report.account = aws.identity().get("Account")
if not report.account:
report.problems.append(f"the AWS sign-in did not say which account it is in: run {login}")
except SigninExpired:
report.signin_expired = True
report.problems.append(f"the AWS sign-in has expired or is missing: run {login}")
Expand Down
4 changes: 3 additions & 1 deletion src/reframe/core/teardown.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ def delete(ctx: Context, consented: list[dict[str, Any]], say: Callable[[str], N
from reframe.transform import teardown as transform_teardown
if digest(inventory(ctx)) != digest(consented):
raise Stop(Outcome.REFUSED, "the list of resources changed after consent; run reframe teardown again to see the new list")
state, transform, result = ctx.state, transform_ids(ctx), {"at": iso(), "steps": []}
state, transform = ctx.state, transform_ids(ctx)
result: dict[str, Any] = {"at": iso(), "steps": []}

def step(name: str, outcome: str) -> None:
say(f" {name}: {outcome}\n")
Expand Down Expand Up @@ -177,6 +178,7 @@ def step(name: str, outcome: str) -> None:
if any(i["from"].startswith("Terraform bootstrap") for i in consented):
deleted = tf.destroy("bootstrap", ctx.changes)["deleted"]
step("state bucket (Terraform)", f"destroyed {len(deleted)}")
left: dict[str, Any]
try:
left = network.leftovers(ctx.aws, ctx.folder.root.name, state["project"])
except NotSent as error:
Expand Down
30 changes: 19 additions & 11 deletions src/reframe/design/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ def data_items(text: str, file: str) -> list[Item]:
val = value.group(1) if value else None
if val and val[0] in "'\"":
val = val[1:-1].replace("''", "'")
items.append(Item(int(m.group(1)), (m.group(2) or "FILLER").upper(), (re.search(r"\bPIC(?:TURE)?\s+(?:IS\s+)?(\S+)", rest, re.I) or [None, ""])[1],
val, ((re.search(rf"\bREDEFINES\s+({NAME})", rest, re.I) or [None, ""])[1]).upper(),
int((re.search(r"\bOCCURS\s+(\d+)", rest, re.I) or [None, 0])[1]), line, file,
((re.search(r"\b(COMP(?:UTATIONAL)?(?:-[1-5])?|BINARY|PACKED-DECIMAL|DISPLAY)\b", rest, re.I) or [None, ""])[1]).upper()))
items.append(Item(int(m.group(1)), (m.group(2) or "FILLER").upper(), _first(r"\bPIC(?:TURE)?\s+(?:IS\s+)?(\S+)", rest),
val, _first(rf"\bREDEFINES\s+({NAME})", rest).upper(),
int(_first(r"\bOCCURS\s+(\d+)", rest, "0")), line, file,
_first(r"\b(COMP(?:UTATIONAL)?(?:-[1-5])?|BINARY|PACKED-DECIMAL|DISPLAY)\b", rest).upper()))
return items


Expand Down Expand Up @@ -129,6 +129,12 @@ class Program:
paragraphs: dict[str, tuple[int, int]] # name -> (first line, last line)


def _first(pattern: str, text: str, default: str = "") -> str:
"""Group 1 of the pattern's first match in the text, ignoring case, or the default when it does not match."""
m = re.search(pattern, text, re.I)
return m.group(1) if m else default


def _copybooks(legacy: Path) -> dict[str, Path]:
return {p.stem.upper(): p for p in legacy.rglob("*") if p.is_file() and p.suffix.lower() in (".cpy", "")
and p.parent.name.lower().startswith("cpy")}
Expand All @@ -144,7 +150,8 @@ def read_program(path: Path, legacy: Path, copybooks: dict[str, Path]) -> Progra
items += data_items(book.read_text(errors="replace"), book.relative_to(legacy).as_posix())
constants = {x.name: (str(x.value), x.file, x.line) for x in items if x.value is not None and x.name != "FILLER"}
body = lines_of(text)
paragraphs, start, name = {}, None, None
paragraphs: dict[str, tuple[int, int]] = {}
start, name = 0, None # start is set with name
procedure = next((i for i, b in enumerate(body) if re.search(r"\bPROCEDURE\s+DIVISION\b", b, re.I)), len(body))
for i in range(procedure + 1, len(body)):
m = re.match(rf"^({NAME})\.\s*$", body[i][:4].strip() and body[i] or "", re.I) # a paragraph name, starting in area A
Expand Down Expand Up @@ -208,9 +215,9 @@ def resolve(program: Program, expr: str, depth: int = 0) -> list[dict[str, Any]]
return [{"value": value.strip(), "how": "constant", "lines": [f"{file}:{line}"]}] if value.strip() else []
for source, line in moves_into(program, name):
values = resolve(program, source, depth + 1)
if depth == 0 and REF.match(source) and values and all(v["value"].upper() == program.name for v in values):
if depth == 0 and (ref := REF.match(source)) and values and all(v["value"].upper() == program.name for v in values):
# a variable the program only ever sets to itself, before transferring away: whoever comes next sends it back
found.append({"value": program.name, "how": "caller", "lines": [f"{program.file}:{line}"], "via": REF.match(source).group(1).upper()})
found.append({"value": program.name, "how": "caller", "lines": [f"{program.file}:{line}"], "via": ref.group(1).upper()})
continue
for v in values:
found.append({**v, "how": v["how"] if v["how"] != "literal" else "moved", "lines": v["lines"] + [f"{program.file}:{line}"]})
Expand Down Expand Up @@ -247,7 +254,7 @@ def _branch(program: Program, line: int) -> tuple[int, int]:
end, depth, started = line, 0, False
for i in range(line, min(len(program.lines), line + 80)):
body = program.lines[i].strip()
word = (re.match(r"^([A-Z-]+)", body, re.I) or [None, ""])[1].upper()
word = _first(r"^([A-Z-]+)", body).upper()
if not started and depth == 0 and (word in ("WHEN", "AND", "OR", "") or body.startswith("(")):
end = i + 1 # more of the condition, or a WHEN stacked on this one: they share the statements that follow
continue
Expand All @@ -268,7 +275,7 @@ def flow(legacy: Path, screens: dict[str, Any]) -> dict[str, Any]:
copybooks = _copybooks(legacy)
programs = {p.stem.upper(): read_program(p, legacy, copybooks) for p in sorted(legacy.rglob("*"))
if p.is_file() and p.suffix.lower() in (".cbl", ".cob")}
by_tran = {}
by_tran: dict[str, dict[str, Any]] = {}
trans = transactions(legacy)
for t in trans:
by_tran.setdefault(t["transaction"], t)
Expand Down Expand Up @@ -308,9 +315,10 @@ def add(kind: str, source: str, target: str, lines: list[str], **extra: Any) ->
keys = []
for s in screens.get("screens") or []:
for k in s["keys"]["handled"]:
prog = programs.get(k["program"])
if not prog:
handler = programs.get(k["program"])
if not handler:
continue
prog = handler
first, last = _branch(prog, k["line"])
targets = []
for var in transfer_vars.get(prog.name, set()):
Expand Down
2 changes: 1 addition & 1 deletion src/reframe/design/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def inventory(legacy: Path) -> dict[str, Any]:
for p in _files(legacy, COBOL_SUFFIXES):
text = p.read_text(errors="replace")
programs[p.stem.upper()] = {"file": rel(p), "copies": _copies(text), "text": text}
screens = []
screens: list[dict[str, Any]] = []
for p in _files(legacy, BMS_SUFFIXES):
for m in read_bms(p.read_text(errors="replace"), rel(p)):
copybook = symbolic.get(m.mapset.upper())
Expand Down
5 changes: 3 additions & 2 deletions src/reframe/design/journeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def domains_of_screens(screens: dict[str, Any], rules: list[dict[str, Any]], req
by_program[str(r.get("program", "")).upper()][r.get("function", "")] += 1
found: dict[str, list[str]] = defaultdict(list)
for s in screens["screens"]:
counts = Counter()
counts: Counter[str] = Counter()
for p in s["programs"]:
counts.update(by_program.get(p["name"].upper(), Counter()))
function = counts.most_common(1)[0][0] if counts else None
Expand Down Expand Up @@ -201,7 +201,8 @@ def run(folder, claude, context: Path | None = None, more=None, plan_only: bool
log = saved.get("log") or []
folder_in = places["analysis"] / "reframe" / "design"
folder_in.mkdir(parents=True, exist_ok=True)
lock, stopped = threading.Lock(), []
lock = threading.Lock()
stopped: list[Any] = []
todo, why = [], []
for key, mine in sorted(by_domain.items()):
data = domain_input(domains.get(key) or {"name": key, "functions": []}, screens, mine, flow, requirements, personas)
Expand Down
2 changes: 1 addition & 1 deletion src/reframe/design/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
problems = check(root, specs, ts)
made = manifest(specs, ts, stack)
same = latest is not None and (latest / "manifest.json").is_file() and json.loads((latest / "manifest.json").read_text()).get("digest") == digest(root)
if same:
if same and latest is not None: # same already needs latest
version, target = have[-1], latest
else:
version = (have[-1] + 1) if have else 1
Expand Down
5 changes: 3 additions & 2 deletions src/reframe/infrastructure/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from __future__ import annotations

import functools
import time
from typing import Any

Expand All @@ -31,7 +32,7 @@ def delete_interfaces(aws: Aws, changes: Changes, vpc_id: str) -> list[str]:
deleted = []
for interface in transform_interfaces(aws, vpc_id):
changes.apply(f"teardown-eni-{interface['id']}", "ec2 delete-network-interface", {"interface": interface["id"], "vpc": vpc_id},
lambda i=interface: aws.write("ec2", "delete-network-interface", "--network-interface-id", i["id"]))
functools.partial(aws.write, "ec2", "delete-network-interface", "--network-interface-id", interface["id"]))
deleted.append(interface["id"])
return deleted

Expand Down Expand Up @@ -117,7 +118,7 @@ def still_exists(aws: Aws, arn: str) -> bool | None:


def leftovers(aws: Aws, run: str, project: str) -> dict[str, list[str]]:
found = {"exists": [], "stale_index": [], "unchecked": []}
found: dict[str, list[str]] = {"exists": [], "stale_index": [], "unchecked": []}
for arn in tagged(aws, run, project):
state = still_exists(aws, arn)
found["exists" if state else "stale_index" if state is False else "unchecked"].append(arn)
Expand Down
10 changes: 5 additions & 5 deletions src/reframe/reconcile/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
VERDICTS = ("correct", "minor", "wrong", "unsure")
DEFECTS = ("real", "not_a_defect", "unsure")

SCHEMA = {"type": "object", "required": ["judgments"], "properties": {"judgments": {"type": "array", "items": {
SCHEMA: dict[str, Any] = {"type": "object", "required": ["judgments"], "properties": {"judgments": {"type": "array", "items": {
"type": "object", "required": ["item", "verdict", "evidence", "lost", "defect", "reason", "read"],
"properties": {
"item": {"type": "string"},
Expand Down Expand Up @@ -296,13 +296,13 @@ def read_settled(folder: RunFolder) -> dict[str, dict[str, str]]:
return {row["id"]: row for row in csv.DictReader(io.StringIO(path.read_text()))}


def final(item: dict[str, Any], judged: dict[str, dict[str, Any]], settled: dict[str, dict[str, str]], with_note: bool = False) -> dict[str, str]:
def final(item: dict[str, Any], judged: dict[str, dict[str, Any]], settled: dict[str, dict[str, str]], with_note: bool = False) -> dict[str, Any]:
"""The item's verdict and defect answer: the judges' shared answer, else the owner's, else "unsettled"."""
answers = [judged[lab]["answers"].get(item["id"]) or {} for lab in sorted(judged)]
owner = settled.get(item["id"]) or {}
verdicts = {a.get("verdict") for a in answers}
verdict = verdicts.pop() if len(verdicts) == 1 else (owner.get("owner_verdict") or "").strip() or "unsettled"
defect = ""
defect: Any = "" # a judge may leave the defect answer out
if with_note:
defects = {a.get("defect") for a in answers}
defect = defects.pop() if len(defects) == 1 else (owner.get("owner_defect") or "").strip() or "unsettled"
Expand All @@ -318,7 +318,7 @@ def tally(group: list[dict[str, Any]]) -> dict[str, Any]:
n = len(group)
counts = Counter(finals[i["id"]]["verdict"] for i in group)
agreed = sum(len({(judged[lab]["answers"].get(i["id"]) or {}).get("verdict") for lab in labels}) == 1 for i in group)
out = {"items": n, **{v: counts.get(v, 0) for v in (*VERDICTS, "unsettled")}, "judges_agreed": agreed}
out: dict[str, Any] = {"items": n, **{v: counts.get(v, 0) for v in (*VERDICTS, "unsettled")}, "judges_agreed": agreed}
if n:
out["correct_share"] = round(counts.get("correct", 0) / n, 2)
out["correct_or_minor_share"] = round((counts.get("correct", 0) + counts.get("minor", 0)) / n, 2)
Expand All @@ -333,7 +333,7 @@ def tally(group: list[dict[str, Any]]) -> dict[str, Any]:
# A note's call (P3-13): "unintended" should be judged real, "deliberate" not a defect.
called = [i for i in notes if i.get("defect_call") and finals[i["id"]]["defect"] in ("real", "not_a_defect")]
calls_agreed = sum((i["defect_call"] == "unintended") == (finals[i["id"]]["defect"] == "real") for i in called)
confidence = defaultdict(Counter)
confidence: defaultdict[str, Counter[str]] = defaultdict(Counter)
for i in recommended:
confidence[i["confidence"] or "none"][finals[i["id"]]["verdict"]] += 1
evidence = {lab: dict(Counter((judged[lab]["answers"].get(i["id"]) or {}).get("evidence") for i in recommended)) for lab in labels}
Expand Down
Loading
Loading