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
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ coverage run -m unittest discover -s tests -t . && coverage report
```

- **ruff** checks for real faults, not style: pyflakes, syntax errors and bugbear (`[tool.ruff.lint]` in `pyproject.toml`).
- **mypy** checks every module except those listed under `[[tool.mypy.overrides]]`, which still have type errors to fix. The list only shrinks: when you fix a module, take it off.
- **mypy** checks every module, with none exempt. Keep it that way: fix a type error rather than adding a `[[tool.mypy.overrides]]` entry.
- **coverage** fails below the floor in `[tool.coverage.report]`. Raise the floor when your tests raise coverage; never lower it.

## How a change is made
Expand Down
6 changes: 0 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,3 @@ files = ["src/reframe"]
ignore_missing_imports = true
warn_unused_ignores = true
warn_redundant_casts = true

# 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.core.commands"]
ignore_errors = true
952 changes: 0 additions & 952 deletions src/reframe/core/commands.py

This file was deleted.

65 changes: 65 additions & 0 deletions src/reframe/core/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""The command handlers behind reframe's CLI (specification section 3), one module per command group:

| Module | Commands |
|----------------|--------------------------------------------|
| `starting` | run, resume, claude and the worker |
| `reading` | status, events, report, compare |
| `answering` | answer |
| `reconciling` | reconcile, review |
| `designing` | design, export |
| `sharing` | publish, reports |
| `tearing_down` | teardown |

The helpers every command shares are here. The command modules look them up through this package
(`commands.say`, `commands.find_run`, `commands._start_worker`, and the commands that start others), never by
importing them, so `reframe.core.commands.<name>` is the one place each is found and replaced in a test.
"""

from __future__ import annotations

import subprocess
import sys

from reframe.core.errors import EXIT_CODES, Stop
from reframe.core.runfolder import RunFolder, find_run


def say(text: str) -> None:
sys.stdout.write(text) # the current stdout, so output can be redirected


def _fail(stop: Stop) -> int:
from reframe.core import ui
ui.error(f"{stop.outcome.value}: {stop.message}")
return EXIT_CODES[stop.outcome]


def _prompt(text: str) -> str:
if not sys.stdin.isatty():
raise EOFError
return input(text)


def _start_worker(folder: RunFolder, task: str = "run") -> int:
log = folder.path("worker.log").open("a")
process = subprocess.Popen([sys.executable, "-m", "reframe", "worker", str(folder.root), "--task", task], stdin=subprocess.DEVNULL,
stdout=log, stderr=log, start_new_session=True, cwd=str(folder.root))
return process.pid


# the commands, after the helpers they look up here
from reframe.core.commands.starting import ( # noqa: E402
_claude_wanted as _claude_wanted, claude, resume, run, start, start_claude_if_ready, start_claude_only, worker)
from reframe.core.commands.reconciling import reconcile, review # noqa: E402
from reframe.core.commands.designing import design, export # noqa: E402
from reframe.core.commands.sharing import publish, reports # noqa: E402
from reframe.core.commands.reading import ( # noqa: E402
CLAUDE_NEXT, NEXT, STATUS_STYLE, STEP_STYLE, _claude_status as _claude_status, _reconcile_status as _reconcile_status,
claude_next, compare, events, report, status)
from reframe.core.commands.answering import answer # noqa: E402
from reframe.core.commands.tearing_down import teardown # noqa: E402

__all__ = ["say", "find_run",
"run", "start", "start_claude_only", "start_claude_if_ready", "resume", "worker", "claude",
"status", "events", "report", "compare", "claude_next", "NEXT", "STATUS_STYLE", "STEP_STYLE", "CLAUDE_NEXT",
"answer", "reconcile", "review", "design", "export", "publish", "reports", "teardown"]
75 changes: 75 additions & 0 deletions src/reframe/core/commands/answering.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""`reframe answer`: a waiting question from AWS Transform or the Claude assessment (specification section 5)."""

from __future__ import annotations

import sys
from typing import Any

from reframe.core import commands
from reframe.core.errors import Stop
from reframe.core.runfolder import RunFolder, iso


def answer(args) -> int:
from reframe.transform import answers
try:
folder = commands.find_run(args.run)
except Stop as stop:
return commands._fail(stop)
pending = folder.load("question.json")
if not pending:
claude_pending = folder.load("claude-question.json") # pipeline 1's question comes first
if claude_pending:
return _answer_claude(folder, claude_pending, args)
commands.say("Nothing is waiting for an answer.\n")
return 0
if pending.get("kind") == "claude":
return _answer_claude(folder, pending, args)
question = answers.Question(pending["id"], pending["kind"], pending["text"], tuple(pending.get("options") or ()),
tuple(pending.get("replies") or ()), pending.get("interaction_origin_id"), pending.get("schema") or {})
if not args.choices and not args.text:
commands.say(f"AWS asks ({question.kind}, since {pending.get('asked_at')}):\n\n{question.text.strip()}\n\n")
for number, label in enumerate(question.options, 1):
commands.say(f" {number}. {label}\n")
hint = ("reframe answer <number> [<number>...]" if question.kind in ("catalog", "select") else "reframe answer <number>")
commands.say("\nAnswer with " + (f"{hint}, or " if question.options else "") + "reframe answer --text \"...\"\n")
return 0
try:
choices = [int(c) for c in args.choices]
reply = answers.interactive(question, choices, args.text)
except ValueError as error:
sys.stderr.write(f"{error}\n")
return 2
folder.save("answer.json", {"id": question.id, "text": reply.text, "reason": reply.reason, "at": iso()})
folder.event("answer_given", id=question.id)
commands.say(f"Answer recorded: {reply.text[:300]}\n")
commands.say("The worker sends it within a minute." if folder.worker_pid() else "Run reframe resume to send it.")
commands.say("\n")
return 0


def _answer_claude(folder: RunFolder, pending: dict[str, Any], args) -> int:
"""A pipeline 2 question (the plugin's preflight answers, the rule-extraction estimate, loading an existing cluster)."""
options = pending.get("options") or []
if not args.choices and not args.text:
commands.say(f"The Claude assessment asks (since {pending.get('asked_at')}):\n\n{pending['text'].strip()}\n\n")
for number, label in enumerate(options, 1):
commands.say(f" {number}. {label}\n")
commands.say("\nAnswer with reframe answer <number>" + (", or reframe answer --text \"...\"" if pending["id"].startswith("claude-preflight") else "") + "\n")
return 0
if args.text and not pending["id"].startswith("claude-preflight"):
sys.stderr.write("this question takes one of the numbered options\n")
return 2
if args.choices:
if len(args.choices) != 1 or not args.choices[0].isdigit() or not 1 <= int(args.choices[0]) <= len(options):
sys.stderr.write(f"choose one number from 1 to {len(options)}\n")
return 2
text = options[int(args.choices[0]) - 1]
text = text.removeprefix("Reframe's answer: ")
else:
text = args.text.strip()
folder.save("claude-answer.json", {"id": pending["id"], "text": text, "reason": "answered with reframe answer", "at": iso()})
folder.event("answer_given", id=pending["id"])
commands.say(f"Answer recorded: {text[:300]}\n")
commands.say("The worker uses it within a minute.\n" if folder.worker_pid("claude") else "Run reframe resume to continue.\n")
return 0
121 changes: 121 additions & 0 deletions src/reframe/core/commands/designing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""`reframe design` and `reframe export` (pipeline 4 and the exports, docs/pipeline-4.md and docs/sharing.md)."""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

from reframe.core import commands
from reframe.core.errors import Outcome, Stop


def design(args) -> int:
"""`reframe design` (docs/pipeline-4.md): a design round, its plan, the package copied out, or a copy's readiness."""
from reframe.core import ui
from reframe.design import handover, package, pipeline
if args.check:
found = handover.readiness(Path(args.check).expanduser())
ui.section(f"Package copy {args.check}")
ui.table(["File", "Placeholders left"], [[k, str(len(v))] for k, v in found["files"].items()] or [["–", "0"]])
if found["drafts"]:
ui.hint(f"{len(found['drafts'])} draft capabilities: confirm them with the owner before building them")
(ui.ok if found["ready"] else ui.hint)("ready for forward engineering" if found["ready"] else f"{found['placeholders']} placeholders to fill in; START-HERE.md says how")
return 0 if found["ready"] else 1
try:
folder = commands.find_run(args.run)
if args.package:
done = package.copy_out(folder, Path(args.package).expanduser().resolve(), args.form)
if done["left"]:
raise Stop(Outcome.REFUSED, "; ".join(done["left"][:5]))
ui.ok(f"Package v{done['version']} copied to {done['path']}: {done['written']} files. Open START-HERE.md there.")
return 0
context = Path(args.context).expanduser().resolve() if args.context else None
claude = None
if not args.plan:
from reframe.claude import preflight
from reframe.reconcile.pipeline import claude_code
report = preflight.check(args.auth, aws_identity=preflight.run_identity(folder) if args.auth == "bedrock" else None)
if not report.ok:
raise Stop(Outcome.REFUSED, report.problems())
claude = claude_code(folder, args.auth)
if args.plan:
value = pipeline.run(folder, claude, context, args.stack, args.plan)
else:
folder.lock("design") # one round at a time: two at once write the same parts and pay Claude twice (26 November 2026)
try:
value = pipeline.run(folder, claude, context, args.stack, args.plan)
finally:
folder.unlock("design")
except (Stop, ValueError) as stop:
return commands._fail(stop if isinstance(stop, Stop) else Stop(Outcome.REFUSED, str(stop)))
ui.section(f"Run {folder.root.name} · the design" + (" · plan" if args.plan else f" · round {value['round']}"))
ui.table(["Stage", "Redone", "Kept"], [[k, ", ".join(x["name"] or "No domain" for x in v["redone"]) or "–", str(len(v["kept"]))]
for k, v in value["stages"].items()])
if args.plan:
ui.hint(value["note"])
return 0
ui.ok(f"What changed: {value['changes']}")
ui.ok(f"Package v{value['package']['version']}" + (" (new)" if value["package"]["new"] else " (unchanged)") + f": {value['package']['path']}")
page = folder.path("outputs/design/index.html")
ui.ok(f"The design page: {page}")
if value.get("problems"):
ui.hint(f"{len(value['problems'])} problems the checks still found; they are on the design page")
if args.open:
subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", str(page)], check=False)
return 0


def export(args) -> int:
"""`reframe export --to xlsx` (docs/sharing.md, section 7): the reconciled results as one workbook; `--to jira` or
`--to azure-devops` (section 8): the design's backlog as that tool's CSV import file. Runs nothing."""
from reframe.core import ui
from reframe.report import export as exporter
if args.to in ("jira", "azure-devops"):
return _export_backlog(args)
try:
folder = commands.find_run(args.run)
given = args.context or (folder.state.get("reconcile") or {}).get("context")
context = Path(given).expanduser().resolve() if given else None
if context and not context.is_dir():
raise Stop(Outcome.REFUSED, f"the context folder {given} does not exist")
target = Path(args.out).expanduser().resolve() if args.out else None
value = exporter.export(folder, target, context)
except Stop as stop:
return commands._fail(stop)
ui.section(f"Run {folder.root.name} · export to Excel")
ui.table(["Sheet", "Rows"], [[k, str(v)] for k, v in value["counts"].items()])
if context:
ui.hint(f"review downloads read from {context}: {len(value['read'])}, with marks on {value['marks']} item(s)")
for i in value["ignored"]:
ui.hint(f"ignored {i['file']}: {i['why']}")
else:
ui.hint("no context folder: the workbook has no reviewers' marks")
ui.ok(f"Workbook: {value['path']}")
if args.open:
subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", str(value["path"])], check=False)
return 0


def _export_backlog(args) -> int:
from reframe.core import ui
from reframe.report import backlog
try:
folder = commands.find_run(args.run)
if args.context:
raise Stop(Outcome.REFUSED, "--context adds reviewers' marks to the xlsx workbook; a backlog is built from the design's final specifications")
value = backlog.export(folder, args.to, Path(args.out).expanduser().resolve() if args.out else None)
except Stop as stop:
return commands._fail(stop)
c = value["counts"]
ui.section(f"Run {folder.root.name} · backlog for {value['tool']}")
rows = [["Epics", str(c["epics"])]] + ([["Features", str(c["features"])]] if args.to == "azure-devops" else []) + [
["Stories", f"{c['stories']} ({c['final']} final)"], ["Requirements", str(c["requirements"])], ["Acceptance criteria", str(c["criteria"])]]
ui.table(["Item", "Count"], rows)
ui.ok(f"Import file: {value['path']}")
ui.hint("Import it with " + ("Jira's CSV import; map Issue ID and Parent so the stories join their epics, and Acceptance Criteria to your field "
"for it (the description holds them too)." if args.to == "jira" else
"Azure DevOps's Import work items (Boards, Queries); the Title 1 to 3 columns make the hierarchy."))
if args.open:
subprocess.run(["open" if sys.platform == "darwin" else "xdg-open", str(value["path"])], check=False)
return 0
Loading
Loading