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
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ jobs:
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- run: PYTHONPATH=src python -m unittest discover -s tests
- run: pip install ruff==0.17.4 && ruff check . && ruff format --check .

plugin:
runs-on: ubuntu-24.04
Expand All @@ -27,7 +28,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
# track the fork main; key the cache on the commit it is at now, so a new commit rebuilds
- run: echo "SYSML_REV=$(git ls-remote "$SYSML_GIT" refs/heads/main | cut -f1)" >> "$GITHUB_ENV"
- run: rev=$(git ls-remote "$SYSML_GIT" refs/heads/main | cut -f1) && test -n "$rev" && echo "SYSML_REV=$rev" >> "$GITHUB_ENV"
- id: cache
uses: actions/cache@v4
with:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ PYTHONPATH=src python -m unittest discover -s tests # bridge and renderer
python tests/acceptance.py # example build + mutations (needs the tools)
python tests/omg_corpus.py # OMG release corpus through the pipeline
claude plugin validate . # marketplace and plugin manifests
ruff check . && ruff format --check . # lint and format (CI pins ruff 0.17.4)
```

## License
Expand Down
5 changes: 5 additions & 0 deletions examples/vehicle/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ STRICT ?= -W --keep-going
SYSML_GIT = https://github.com/MichaelD-42/sysml-v2-rs

MODEL := $(shell find model -name '*.sysml' | sort)
# make splits file names on spaces, so `my part.sysml` would become two missing files
$(if $(shell find model -name '*.sysml' -name '* *'),$(error model file names must not contain spaces; rename: $(shell find model -name '*.sysml' -name '* *')))
RESULTS := $(wildcard test-results/*.xml)
GEN := docs/_generated
# Usages whose internal structure is drawn, by qualified name (e.g. MyLogical::system MyFunctions::operate)
Expand Down Expand Up @@ -45,6 +47,9 @@ render: build/model.json
# start empty: a renamed subject or a dropped DIAGRAMS entry must not leave its old picture behind
rm -f $(GEN)/*.svg
$(SYSML2KIT) usecases build/model.json $(GEN)
@# each diagram is saved under its last name segment, so two entries ending alike would overwrite each other
@dups=$$(for d in $(DIAGRAMS); do echo $${d##*::}; done | sort | uniq -d); \
if [ -n "$$dups" ]; then echo "DIAGRAMS: more than one entry ends in $$dups" >&2; exit 1; fi
for d in $(DIAGRAMS); do $(SYSML) diagram --internal $$d model > $(GEN)/$$(echo $$d | sed 's/.*:://').svg || exit 1; done

# two passes: the trace graph needs the complete need set, RST needs included
Expand Down
2 changes: 1 addition & 1 deletion plugins/sysml-rflp/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sysml-rflp",
"displayName": "SysML v2 RFLP",
"version": "0.1.0",
"version": "0.1.1",
"description": "Author, lint and render SysML v2 models, trace them to sphinx-needs, and derive use cases, system requirements, functions and logical architecture from customer requirements (RFLP)",
"author": { "name": "Michael Dold" },
"repository": "https://github.com/MichaelD-42/sysml2-kit",
Expand Down
20 changes: 16 additions & 4 deletions plugins/sysml-rflp/scripts/check_tools.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
"""SessionStart: in an RFLP project, say which pipeline tools are missing (silent when all are there)."""
"""SessionStart: in an RFLP project, say which pipeline tools are missing and whether the MCP server can see the model."""

import os
import shutil
import sys
from pathlib import Path

project = Path(os.environ.get("CLAUDE_PROJECT_DIR", "."))
if not (project / "model").is_dir() and not list(project.glob("*/model/trace.sysml")):
sys.exit(0)
missing = [tool for tool in ("sysml", "sysml2kit", "test-reports", "sphinx-build") if not shutil.which(tool)]
nested = [trace.parent.parent for trace in project.glob("*/model/trace.sysml")]
if not (project / "model").is_dir():
if not nested:
sys.exit(0)
# the plugin starts `sysml mcp --project model`, relative to where Claude was started
print(
f"sysml-rflp: the model is in a subdirectory; start Claude in {' or '.join(map(str, nested))} "
"so the sysml MCP server (find, relations, outline) sees it."
)
missing = [
tool
for tool in ("sysml", "sysml2kit", "test-reports", "sphinx-build")
if not shutil.which(tool)
]
if missing:
print(
f"sysml-rflp: missing on PATH: {', '.join(missing)}. "
Expand Down
13 changes: 11 additions & 2 deletions plugins/sysml-rflp/scripts/lint_on_edit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""PostToolUse: after a .sysml file is written, run `sysml check` on its project's model/ and report errors to Claude."""

import json
import shutil
import subprocess
Expand All @@ -12,7 +13,15 @@
model = next((p for p in path.resolve().parents if p.name == "model"), None)
if model is None:
sys.exit(0)
result = subprocess.run(["sysml", "--color", "never", "check", str(model)], capture_output=True, text=True)
result = subprocess.run(
["sysml", "--color", "never", "check", str(model)],
check=False,
capture_output=True,
text=True,
)
if result.returncode != 0:
print(f"sysml check {model} failed after editing {path.name}:\n{result.stdout}{result.stderr}", file=sys.stderr)
print(
f"sysml check {model} failed after editing {path.name}:\n{result.stdout}{result.stderr}",
file=sys.stderr,
)
sys.exit(2) # feeds stderr back to Claude
2 changes: 1 addition & 1 deletion plugins/sysml-rflp/skills/sysml-author/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Create and change SysML v2 models (.sysml files) - use cases, requi

# SysML v2 authoring

`references/patterns.sysml` is a checked example of every construct the pipeline maps; copy from it. The `sysml` MCP server answers syntax and name questions: `notation` (how to write a construct), `visible_names` (what resolves at a point), `outline`, `library_search`, `check`. To read an existing model, use `find` (elements by kind, namespace, name, or a relation they lack: `kind: RequirementUsage, without: verifies`) and `relations` (every link of one element both ways, by qualified or short name) instead of opening files.
`references/patterns.sysml` is a checked example of every construct the pipeline maps; copy from it. The `sysml` MCP server answers syntax and name questions: `notation` (how to write a construct), `visible_names` (what resolves at a point), `outline`, `library_search`, `check`. To read an existing model, use `find` (elements by kind, namespace, name, or a relation they lack: `kind: RequirementUsage, without: verifies`) and `relations` (every link of one element both ways, by qualified or short name) instead of opening files. If the server says it has no tool `find`, the installed `sysml` predates these tools: run `make tools`.

## Conventions

Expand Down
5 changes: 5 additions & 0 deletions plugins/sysml-rflp/templates/project/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ STRICT ?= -W --keep-going
SYSML_GIT = https://github.com/MichaelD-42/sysml-v2-rs

MODEL := $(shell find model -name '*.sysml' | sort)
# make splits file names on spaces, so `my part.sysml` would become two missing files
$(if $(shell find model -name '*.sysml' -name '* *'),$(error model file names must not contain spaces; rename: $(shell find model -name '*.sysml' -name '* *')))
RESULTS := $(wildcard test-results/*.xml)
GEN := docs/_generated
# Usages whose internal structure is drawn, by qualified name (e.g. MyLogical::system MyFunctions::operate)
Expand Down Expand Up @@ -45,6 +47,9 @@ render: build/model.json
# start empty: a renamed subject or a dropped DIAGRAMS entry must not leave its old picture behind
rm -f $(GEN)/*.svg
$(SYSML2KIT) usecases build/model.json $(GEN)
@# each diagram is saved under its last name segment, so two entries ending alike would overwrite each other
@dups=$$(for d in $(DIAGRAMS); do echo $${d##*::}; done | sort | uniq -d); \
if [ -n "$$dups" ]; then echo "DIAGRAMS: more than one entry ends in $$dups" >&2; exit 1; fi
for d in $(DIAGRAMS); do $(SYSML) diagram --internal $$d model > $(GEN)/$$(echo $$d | sed 's/.*:://').svg || exit 1; done

# two passes: the trace graph needs the complete need set, RST needs included
Expand Down
2 changes: 1 addition & 1 deletion plugins/sysml-rflp/templates/project/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
sphinx==9.1.1
sphinx-needs==9.2.0
ub-test-reports==2.0.0
sysml2kit @ git+https://github.com/MichaelD-42/[email protected].0
sysml2kit @ git+https://github.com/MichaelD-42/[email protected].1
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "sysml2kit"
version = "0.1.0"
version = "0.1.1"
description = "Bridge SysML v2 models into sphinx-needs traceability and render use case and trace diagrams"
readme = "README.md"
license = "MIT"
Expand Down
13 changes: 10 additions & 3 deletions src/sysml2kit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,21 @@
def main(argv=None):
parser = argparse.ArgumentParser(prog="sysml2kit", description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("needs", help="interchange JSON (`sysml export`) -> sphinx-needs needs.json")
p = sub.add_parser(
"needs", help="interchange JSON (`sysml export`) -> sphinx-needs needs.json"
)
p.add_argument("export")
p.add_argument("output")
p.add_argument("model_files", nargs="+", help="the .sysml files, for source locations")
p.add_argument(
"model_files", nargs="+", help="the .sysml files, for source locations"
)
p = sub.add_parser("usecases", help="one use case diagram SVG per subject")
p.add_argument("export")
p.add_argument("output_dir")
p = sub.add_parser("trace", help="RFLP trace graph SVG from a sphinx-needs needs.json (`sphinx-build -b needs`)")
p = sub.add_parser(
"trace",
help="RFLP trace graph SVG from a sphinx-needs needs.json (`sphinx-build -b needs`)",
)
p.add_argument("needs_json")
p.add_argument("output")
args = parser.parse_args(argv)
Expand Down
3 changes: 2 additions & 1 deletion src/sysml2kit/needs.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@
"Trace::Realizes": "realizes",
"Trace::Verifies": "verifies",
}
COMMENT = re.compile(r"/\*.*?\*/|//[^\n]*", re.S)
# multi-line note `//* */` first, or `//` would take only its first line
COMMENT = re.compile(r"//\*.*?\*/|/\*.*?\*/|//[^\n]*", re.DOTALL)
# reStructuredText inline markup; doc text is plain text, so these are escaped
RST_INLINE = re.compile(r"([\\*`_|])")

Expand Down
43 changes: 29 additions & 14 deletions src/sysml2kit/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,31 @@ def _text(x, y, text, cls="", anchor="middle"):


def use_cases(elements):
"""[(subject name, [(use case need id, name, [actor names])])] from SysML interchange JSON."""
"""[(subject title, [(use case need id, name, [actor names])])] from SysML interchange JSON.

Use cases are grouped by subject name and type: untyped `subject vehicle;` in several use
cases is one subject, while `vehicle : Car` and `vehicle : Truck` are two, titled with their type.
"""
by_id = {e["@id"]: e for e in elements}

def member_name(membership):
def member(membership):
target = membership.get("ownedMemberElement") or membership.get(
"ownedRelatedElement"
)
target = target[0] if isinstance(target, list) and target else target
return by_id.get(target["@id"], {}).get("name") if target else None
return by_id.get(target["@id"], {}) if target else {}

def member_name(membership):
return member(membership).get("name")

def subject_key(membership):
subject = member(membership)
types = subject.get("type") or []
types = types if isinstance(types, list) else [types]
typed = [by_id[t["@id"]] for t in types if t["@id"] in by_id]
return subject.get("name"), (
typed[0].get("qualifiedName") or typed[0].get("name") if typed else None
)

subjects = {}
for e in elements:
Expand All @@ -50,17 +66,11 @@ def member_name(membership):
memberships = [
by_id[m["@id"]] for m in e.get("ownedMembership", []) if m["@id"] in by_id
]
subject = (
next(
(
member_name(m)
for m in memberships
if m["@type"] == "SubjectMembership"
),
None,
)
or "system"
name, type_ = next(
(subject_key(m) for m in memberships if m["@type"] == "SubjectMembership"),
(None, None),
)
subject = (name or "system", type_)
actors = [
member_name(m) for m in memberships if m["@type"] == "ActorMembership"
]
Expand All @@ -72,7 +82,12 @@ def member_name(membership):
[a for a in actors if a],
)
)
return sorted((s, sorted(ucs)) for s, ucs in subjects.items())
names = [name for name, _ in subjects]
# the type goes into the title only where the name alone would merge two subjects
return sorted(
(f"{name} : {type_}" if type_ and names.count(name) > 1 else name, sorted(ucs))
for (name, type_), ucs in subjects.items()
)


def use_case_svg(subject, cases):
Expand Down
43 changes: 34 additions & 9 deletions tests/acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Run: python tests/acceptance.py
"""

import json
import os
import re
import shutil
Expand All @@ -29,7 +30,7 @@ def build(target, edit=None):
if edit:
edit(work)
args = ["make", "-C", str(work), target] + [f"{k}={v}" for k, v in TOOLS.items()]
result = subprocess.run(args, capture_output=True, text=True)
result = subprocess.run(args, check=False, capture_output=True, text=True)
return result.returncode, result.stdout + result.stderr, work


Expand Down Expand Up @@ -103,6 +104,22 @@ def edit(work):
replace("test-results/junit.xml", 'value="STC-004"', 'value="STC-099"'),
r"unknown outgoing link 'STC-099'",
),
(
"two diagrams ending in the same name fail instead of overwriting each other",
"render",
replace(
"Makefile",
"DIAGRAMS := VehicleLogical::vehicle",
"DIAGRAMS := VehicleLogical::vehicle Other::vehicle",
),
r"more than one entry ends in vehicle",
),
(
"a model file name with a space fails with what to rename",
"lint",
lambda work: (work / "model/my parts.sysml").write_text("package Spaced;\n"),
r"must not contain spaces; rename: model/my parts\.sysml",
),
(
"satisfy end without a short name fails the bridge",
"all",
Expand All @@ -125,10 +142,10 @@ def main():
html = (work / "docs/_build/html/model.html").read_text()
checks = {
"SR-003 shows its satisfying component": re.search(
r'id="SR-003".*?satisfied by.*?LC-001', html, re.S
r'id="SR-003".*?satisfied by.*?LC-001', html, re.DOTALL
),
"SR-003 shows its system test": re.search(
r'id="SR-003".*?verified by.*?STC-003', html, re.S
r'id="SR-003".*?verified by.*?STC-003', html, re.DOTALL
),
"diagrams are embedded": all(
f"_images/{n}.svg" in html
Expand Down Expand Up @@ -162,8 +179,10 @@ def incremental(work):
remake = ["make", "-C", str(work), "all"] + [f"{k}={v}" for k, v in TOOLS.items()]
use_cases = work / "model/requirements/use_cases.sysml"
original = use_cases.read_text()
use_cases.write_text(original.replace("subject vehicle;", "subject car;")) # every use case
result = subprocess.run(remake, capture_output=True, text=True)
use_cases.write_text(
original.replace("subject vehicle;", "subject car;")
) # every use case
result = subprocess.run(remake, check=False, capture_output=True, text=True)
out = result.stdout + result.stderr
failed = report(
"a renamed subject's old diagram is gone, so the page pointing at it fails",
Expand All @@ -174,15 +193,15 @@ def incremental(work):
)
use_cases.write_text(original)
(work / "test-results/junit.xml").unlink()
result = subprocess.run(remake, capture_output=True, text=True)
result = subprocess.run(remake, check=False, capture_output=True, text=True)
stale = "testresult" in (work / "docs/_generated/results-needs.json").read_text()
failed += report(
"deleted test results disappear on rebuild",
result.returncode == 0 and not stale,
result.stdout + result.stderr,
)
(work / "model/verification/system_tests.sysml").unlink()
result = subprocess.run(remake, capture_output=True, text=True)
result = subprocess.run(remake, check=False, capture_output=True, text=True)
out = result.stdout + result.stderr
return failed + report(
"deleted model file fails the rebuild (sysreq-verified)",
Expand All @@ -202,9 +221,15 @@ def hook(work):
)(work)

def run(path):
event = '{"tool_name": "Edit", "tool_input": {"file_path": "%s"}}' % path
event = json.dumps(
{"tool_name": "Edit", "tool_input": {"file_path": str(path)}}
)
return subprocess.run(
[sys.executable, str(script)], input=event, capture_output=True, text=True
[sys.executable, str(script)],
input=event,
check=False,
capture_output=True,
text=True,
)

broken, other = run(target), run(work / "docs/index.rst")
Expand Down
7 changes: 4 additions & 3 deletions tests/omg_corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from sysml2kit.needs import BridgeError, convert # noqa: E402
from sysml2kit.render import use_case_svg, use_cases # noqa: E402
from sysml2kit.needs import BridgeError, convert
from sysml2kit.render import use_case_svg, use_cases

RELEASE_TAG = "2026-09.1"
SYSML = os.environ.get("SYSML", "sysml")
Expand Down Expand Up @@ -45,6 +45,7 @@ def main():
root = release / "sysml" / "src" / folder
check = subprocess.run(
[SYSML, "--color", "never", "check", str(root)],
check=False,
capture_output=True,
text=True,
)
Expand All @@ -58,7 +59,7 @@ def main():
failures += not ok
files = sorted(str(p) for p in root.rglob("*.sysml"))
export = subprocess.run(
[SYSML, "export", *files], capture_output=True, text=True
[SYSML, "export", *files], check=False, capture_output=True, text=True
)
if export.returncode != 0:
print(f"FAIL export {folder}: {export.stderr[-500:]}")
Expand Down
Loading
Loading