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
6 changes: 6 additions & 0 deletions src/reframe/design/designpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ def draw(folder, value: dict[str, Any]) -> Path:
if stack else "Target stack: not given yet, so the data contracts show neutral types.")
notes = " ".join(e(n) for n in value.get("stack_notes") or [] if stack)
contracts = "".join(contract_block(x) for x in value["contracts"].values())
placed = (folder.load("design/order.json") or {}).get("order") or []
replacement = _table([f'<tr><td>{p["position"]}</td><td><a href="#{anchor(p["key"])}">{e(p["title"])}</a></td><td>{e(p["wave_name"])}</td>'
f'<td class="small">{e(p["reason"])}</td></tr>' for p in placed], ["#", "Capability", "Wave", "Why here"]) if placed else \
'<p class="muted small">None yet.</p>'
contracts_how = ("The tables and entities the capabilities' code uses, as typed records: the tables read from the SQL DDL with no model, the "
"entities by a Claude step whose every cited line Reframe checked." if any(x.get("kind") for x in value["contracts"].values()) else
"The copybooks the capabilities' programs copy, as typed records, read from the source with no model.")
Expand Down Expand Up @@ -196,6 +200,8 @@ def draw(folder, value: dict[str, Any]) -> Path:
<div class="filters"><input id="q" type="search" placeholder="Find words in the specifications" aria-label="Find">
<select id="status" aria-label="Status"><option value="">Final and draft</option><option value="final">Final</option><option value="draft">Draft</option></select>
<select id="domain" aria-label="Domain"><option value="">Every domain</option>{options}</select><span class="muted small" id="shown"></span></div>
<h2 id="order">Order of replacement</h2><p class="muted small">From each capability's risk and what it touches, with no model: read-only first, then
updates, then money, security and audit; a capability that shares a data contract or a screen with one already placed follows it.</p>{replacement}
{''.join(body_parts)}
<h2>Data contracts</h2><p class="muted small">{contracts_how}</p>{contracts}
<h2>What the checks still found</h2><ul>{problems}{more}</ul>
Expand Down
77 changes: 77 additions & 0 deletions src/reframe/design/order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Pipeline 4, stage D11: the order of replacement (P4-12, docs/pipeline-4.md section 4 D11). No model.

Each capability has a risk and the list of what it touches (P3-24: money, card data, personal data, security, audit,
record updates, reporting only). Reframe orders the capabilities for replacement in three waves:

1. **Read-only:** it touches reporting only, or nothing on the list, and its risk is low: reports and inquiry screens.
2. **Updates:** it updates records or holds card or personal data, and touches no money, security or audit.
3. **Money, security and audit last:** it touches any of them, or its risk is high (a compliance rule).

Within a wave, lower risk comes first, then final capabilities before drafts, then the specification's own order. A
capability that shares a data contract or a screen with one already placed follows it at once, so what shares data
and screens is replaced together. Each place says why, in words.

design/order.json: {"order": [{"key", "position", "wave", "reason", "with"}], "waves": {...}}
"""

from __future__ import annotations

from typing import Any

FILE = "design/order.json"
WAVES = {1: "read-only", 2: "updates", 3: "money, security and audit"}
LAST = {"money", "security", "audit"}
UPDATES = {"updates_records", "card_data", "personal_data"}
WORDS = {"money": "money", "card_data": "card data", "personal_data": "personal data", "security": "security", "audit": "audit",
"updates_records": "record updates", "reporting_only": "reporting only"}
RISK = {"low": 0, "": 1, "medium": 1, "high": 2}


def wave(s: dict[str, Any]) -> int:
touches = set(s.get("touches") or [])
if touches & LAST or s.get("risk") == "high":
return 3
if touches & UPDATES or s.get("risk") == "medium":
return 2
return 1


def shared(a: dict[str, Any], b: dict[str, Any]) -> list[str]:
"""The data contracts and screens two capabilities share."""
books = {c["copybook"] for c in a.get("contracts") or []} & {c["copybook"] for c in b.get("contracts") or []}
screens = {x["id"] for x in a.get("screens") or []} & {x["id"] for x in b.get("screens") or []}
return sorted(books) + sorted(screens)


def why(s: dict[str, Any], w: int) -> str:
touches = [WORDS.get(t, t) for t in s.get("touches") or []]
what = f"it touches {', '.join(touches)}" if touches else "it touches nothing on the list"
risk = f"{s['risk']} risk" if s.get("risk") else "risk not rated"
lead = {1: "Read-only, so first", 2: "It changes data, so after the read-only capabilities",
3: "Money, security or audit, so last"}[w]
return f"{lead}: {what}; {risk}."


def order(specs: list[dict[str, Any]]) -> dict[str, Any]:
"""The replacement order of the specifications, each place with its wave and reason."""
index = {s["key"]: n for n, s in enumerate(specs)}
base = sorted(specs, key=lambda s: (wave(s), RISK.get(s.get("risk") or "", 1), s.get("status") != "final", index[s["key"]]))
placed: list[dict[str, Any]] = []
done: set[str] = set()
for s in base:
if s["key"] in done:
continue
queue: list[tuple[dict[str, Any], dict[str, Any] | None]] = [(s, None)]
while queue:
x, after = queue.pop(0)
if x["key"] in done:
continue
done.add(x["key"])
w = wave(x)
reason = why(x, w)
if after:
reason += f" Follows {after['title']}: they share {', '.join(shared(x, after))}."
placed.append({"key": x["key"], "title": x["title"], "position": len(placed) + 1, "wave": w, "wave_name": WAVES[w],
"reason": reason, "with": after["key"] if after else ""})
queue += [(y, x) for y in base if y["key"] not in done and wave(y) == w and shared(x, y)]
return {"order": placed, "waves": {WAVES[w]: sum(1 for p in placed if p["wave"] == w) for w in WAVES}}
35 changes: 26 additions & 9 deletions src/reframe/design/package.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,14 @@ def design_md(s: dict[str, Any], books: dict[str, Any]) -> str:
"## Testing", "", f"Every acceptance criterion in requirements.md is a test named by its ID ({len(s['acceptance'])} in all)."])


def order_line(s: dict[str, Any]) -> list[str]:
"""Where the capability comes in the order of replacement (P4-12), and why; nothing when there is no order."""
p = s.get("replacement")
return [f"**Order of replacement:** {p['position']} of {p['of']}, {p['wave_name']}. {p['reason']}", ""] if p else []


def tasks_md(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + task_lines(s, ts, numbered=True)) + "\n"
return "\n".join([f"# Implementation plan: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + task_lines(s, ts, numbered=True)) + "\n"


def spec_md(s: dict[str, Any], books: dict[str, Any]) -> str:
Expand Down Expand Up @@ -381,7 +387,7 @@ def speckit_plan(s: dict[str, Any], books: dict[str, Any], stack: dict[str, Any]


def speckit_tasks(s: dict[str, Any], ts: list[dict[str, Any]]) -> str:
out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), "", "Each task names the role that does it; the role files are in .claude/agents/.", ""]
out = [f"# Tasks: {s['title']} ({s['id']})", "", status_line(s), ""] + order_line(s) + ["Each task names the role that does it; the role files are in .claude/agents/.", ""]
for t in ts:
out.append(f"- [ ] {t['id']} [{t['role']}] {md(t['title'])}. Requirements: {', '.join(t['requirements'])}"
+ (f". Rules: {', '.join(t['rules'])}" if t["rules"] else "") + (f". Criteria: {', '.join(t['criteria'])}" if t.get("criteria") else "")
Expand Down Expand Up @@ -463,11 +469,17 @@ def traceability_md(specs: list[dict[str, Any]], ts: dict[str, list[dict[str, An


def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack: dict[str, Any] | None, journeys: list[dict[str, Any]],
prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None) -> dict[str, list[dict[str, Any]]]:
prototype: Path | None, project: str, context: dict[str, str], programs: dict[str, list[str]] | None = None,
replacement: dict[str, Any] | None = None) -> dict[str, list[dict[str, Any]]]:
"""Every form of the package under root. Returns the tasks by capability."""
placed = {p["key"]: p for p in (replacement or {}).get("order") or []}
specs = [{**s, "replacement": {**placed[s["key"]], "of": len(placed)}} if s["key"] in placed else s for s in specs]
by_order = sorted(specs, key=lambda s: (s["replacement"]["position"] if s.get("replacement") else len(specs) + 1))
ordered = [f"{s['replacement']['position']}. {s['id']} {md(s['title'])} ({s['replacement']['wave_name']}): {s['replacement']['reason']}"
for s in by_order if s.get("replacement")]
datasets = {s["id"]: golden.dataset(s) for s in specs}
ts = {s["id"]: tasks(s, datasets[s["id"]]) for s in specs}
contracts = "# Data contracts\n\nThe copybooks the capabilities' programs copy, as typed records, read from the legacy source.\n\n" + \
contracts = "# Data contracts\n\nThe copybooks, tables or entities the capabilities' code uses, as typed records, read from the legacy source.\n\n" + \
"\n".join(contract_md(c) for c in books.values())
trace = traceability_md(specs, ts)
product = product_md(specs, journeys, project, context.get("personas", ""), context.get("decisions", ""))
Expand Down Expand Up @@ -512,8 +524,9 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
"## Conventions", ""] + conventions() + ["", "## House conventions", "", handover.house(context.get("style", "")), "",
"## Skills", "", "In `.claude/skills/`: " + ", ".join(f"`{n}`" for n in handover.SKILLS) + ". Fill in their placeholders first; START-HERE.md says how.", "",
"## Capabilities", "", index, ""])
files["claude-code/tasks.md"] = "# Tasks\n\nBuild final capabilities first. Each task names its role and the IDs it implements.\n\n" + "\n\n".join(
f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(task_lines(s, ts[s["id"]])) for s in specs) + "\n"
files["claude-code/tasks.md"] = "# Tasks\n\n" + ("Build the capabilities in the order of replacement below, from their risk and what they touch (P4-12). "
if ordered else "Build final capabilities first. ") + "Each task names its role and the IDs it implements.\n\n" + "\n\n".join(
f"## {s['id']} {md(s['title'])} ({s['status']})\n\n" + "\n".join(order_line(s) + task_lines(s, ts[s["id"]])) for s in by_order) + "\n"
for s in specs:
files[f"claude-code/specs/{s['folder']}.md"] = spec_md(s, books)
if has_ui:
Expand All @@ -527,9 +540,12 @@ def write(root: Path, specs: list[dict[str, Any]], books: dict[str, Any], stack:
"3. Every requirement, rule, acceptance criterion and task keeps its ID, so the build stays traceable to the legacy source (traceability.md).",
"4. The target stack is the engineer's: " + (f"{stack['stack']}." if stack else "not given yet; nothing that depends on it is built until it is."),
"5. Final capabilities (signed off) are built to as written; draft ones are confirmed with the owner first.",
"6. Order of replacement: final capabilities first; the risk-ranked order (P4-12) will replace this when it exists.",
("6. Order of replacement: the order below, from each capability's risk and what it touches (P4-12): read-only first, then updates, then money, "
"security and audit; capabilities that share data or screens are built together. Draft ones are confirmed with the owner first."
if ordered else "6. Order of replacement: final capabilities first."),
"7. A business rule is kept exactly; a historical artifact is carried only after asking.", "", "## Roles", ""]
+ [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + ["", "## Technical context", "", handover.technical_context(stack), "",
+ [f"- `{r}`: {ROLES[r][1]}" for r in ROLES] + (["", "## Order of replacement", ""] + ordered if ordered else [])
+ ["", "## Technical context", "", handover.technical_context(stack), "",
"## House conventions", "", handover.house(context.get("style", "")), "", "## Conventions", ""] + conventions()) + "\n"
for role in ROLES:
files[f"spec-kit/.claude/agents/{role}.md"] = role_md(role)
Expand Down Expand Up @@ -667,7 +683,8 @@ def run(folder, context: Path | None = None, notes: str = "") -> dict[str, Any]:
from reframe.source import profile
stack_profile = profile.of_run(folder) # START-HERE names the stack (docs/any-legacy.md, section 5.5)
told = {**read_context(context), "legacy": f"{stack_profile['words']['languages']}, {stack_profile.get('family', 'mainframe')}"}
ts = write(root, specs, books, stack, journeys, prototype, project, told, programs)
from reframe.design import order
ts = write(root, specs, books, stack, journeys, prototype, project, told, programs, folder.load(order.FILE))
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)
Expand Down
2 changes: 2 additions & 0 deletions src/reframe/design/specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,8 @@ def one(item) -> None:
"problems": batch_problems + schema_problems + found,
"steps": len(todo), "cost_usd": round(sum(x.get("cost_usd") or 0 for x in log), 2)}
folder.save(FILE, value)
from reframe.design import order
folder.save(order.FILE, order.order(specs)) # the order of replacement (P4-12), from risk and what each touches
value["full"] = specs
value["contracts"] = books
value["round"] = told
Expand Down
77 changes: 77 additions & 0 deletions tests/design/test_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""P4-12: risk and replacement order (docs/pipeline-4.md, section 4 D11). Capabilities are ordered for replacement from
their risk and what they touch, read-only first and money, security and audit last, shared data and screens kept
together; the order and its reasons are on the design page and in the package's constitution and tasks."""
import unittest
from pathlib import Path

from reframe.design import order, pipeline
from tests.design.test_pipeline import RoundsTest


def cap(key, risk="", touches=(), books=(), screens=(), status="draft"):
return {"key": key, "title": key.title(), "risk": risk, "touches": list(touches), "status": status,
"contracts": [{"copybook": b} for b in books], "screens": [{"id": s} for s in screens]}


class OrderTest(unittest.TestCase):
def test_read_only_first_then_updates_then_money_security_and_audit(self):
found = order.order([cap("pay", "high", ["money"]), cap("report", "low", ["reporting_only"]), cap("update", "medium", ["updates_records"]),
cap("signon", "high", ["security"]), cap("inquiry", "low")])
self.assertEqual([(p["key"], p["wave_name"]) for p in found["order"]],
[("report", "read-only"), ("inquiry", "read-only"), ("update", "updates"),
("pay", "money, security and audit"), ("signon", "money, security and audit")])
self.assertEqual(found["waves"], {"read-only": 2, "updates": 1, "money, security and audit": 2})
first = found["order"][0]["reason"]
self.assertEqual(first, "Read-only, so first: it touches reporting only; low risk.")
self.assertIn("Money, security or audit, so last: it touches money; high risk.", found["order"][3]["reason"])

def test_within_a_wave_lower_risk_then_final_first(self):
found = order.order([cap("b", "medium", ["card_data"]), cap("a", "low", ["personal_data"], status="draft"),
cap("c", "low", ["personal_data"], status="final")])
self.assertEqual([p["key"] for p in found["order"]], ["c", "a", "b"])

def test_shared_data_and_screens_follow_at_once(self):
found = order.order([cap("view", "low", books=["ACCT"]), cap("list", "low", screens=["S-LIST"]), cap("detail", "low", books=["ACCT"]),
cap("other", "low", screens=["S-LIST"])])
self.assertEqual([p["key"] for p in found["order"]], ["view", "detail", "list", "other"])
detail = next(p for p in found["order"] if p["key"] == "detail")
self.assertEqual(detail["with"], "view")
self.assertTrue(detail["reason"].endswith("Follows View: they share ACCT."))

def test_sharing_never_pulls_a_capability_into_an_earlier_wave(self):
found = order.order([cap("view", "low", books=["ACCT"]), cap("pay", "high", ["money"], books=["ACCT"]), cap("report", "low")])
self.assertEqual([p["key"] for p in found["order"]], ["view", "report", "pay"])


class InThePackageTest(RoundsTest):
"""On the design fixture (sign-on, high risk for security; the account view, not rated): the page and the package."""

def test_the_order_on_the_page_and_in_the_package(self):
value = pipeline.run(self.folder, self.claude)
placed = self.folder.load(order.FILE)["order"]
self.assertEqual([p["key"] for p in placed], ["rec/Accounts/View#1", "rec/Access/SignOn#1"]) # security last
page = self.folder.path("outputs/design/index.html").read_text()
self.assertIn('<h2 id="order">Order of replacement</h2>', page)
self.assertIn("Money, security or audit, so last: it touches security; high risk.", page)
root = Path(value["package"]["path"])
constitution = (root / "spec-kit/.specify/memory/constitution.md").read_text()
self.assertIn("## Order of replacement", constitution)
self.assertIn("6. Order of replacement: the order below", constitution)
self.assertNotIn("will replace this when it exists", constitution)
tasks = (root / "claude-code/tasks.md").read_text()
self.assertLess(tasks.index("## VA-C01 View an account"), tasks.index("## SIG-C01 Sign on")) # the account view's tasks come first
self.assertIn("**Order of replacement:** 1 of 2, read-only. Read-only, so first: it touches nothing on the list; risk not rated.", tasks)
kiro = next((root / "kiro/.kiro/specs").glob("*sign*/tasks.md")).read_text()
self.assertIn("**Order of replacement:** 2 of 2, money, security and audit.", kiro)
speckit = next((root / "spec-kit/specs").glob("*sign*/tasks.md")).read_text()
self.assertIn("**Order of replacement:** 2 of 2", speckit)


def load_tests(loader, tests, pattern):
suite = loader.loadTestsFromTestCase(OrderTest)
suite.addTest(InThePackageTest("test_the_order_on_the_page_and_in_the_package"))
return suite


if __name__ == "__main__":
unittest.main()