← Files RungstoneARCHIVED FILE

skills/rungstone-ops/scripts/_shared/export.py

5.42 KB · Nov 14, 2026 · 01:10 UTC

↓ Download file

"""
export.py - package approved Rungstone deliverables for the vendor IDE.

Refuses (exit 2) while any high-risk review item is open.  Copies the given
files into export/<timestamp>/ next to .rungstone/, never modifies the
originals, and writes MANIFEST.md (files + sha256, review decisions, open
medium/low items, verification label, safety exclusions).  Nothing is sent
anywhere and nothing is downloaded to a controller: the engineer imports the
files into Studio 5000 / TIA Portal / CODESYS / TwinCAT / the HMI tool.

Usage:  export.py FILE [FILE ...] [--dir PROJECT_DIR] [--out export]
"""

import argparse
import datetime as _dt
import json
import os
import re
import shutil
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import state  # noqa: E402

SAFETY_WRITE_RE = re.compile(r"\b(ESTOP|DCS|DCST|DCSTM|DCSRT|DCM|ESTOP1|TWO_H_EN|MUTING|SF_EmergencyStop|SF_\w+)\s*\(", re.I)


NOT_FOR_PRODUCTION = "Not for use on a production system without review and testing by a qualified engineer."

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("files", nargs="+")
    ap.add_argument("--dir", help="project folder containing .rungstone/")
    ap.add_argument("--out", default="export")
    args = ap.parse_args(argv)

    d = state.find_dir(args.dir)
    if d is None:
        print(json.dumps({"exported": False, "reason": "no .rungstone/ state found; run state.py init first"}))
        return 1
    hi = state.open_items(d, "high")
    if hi:
        print(json.dumps({"exported": False, "blocked": True,
                          "reason": "%d high-risk review item(s) open; approve, edit or reject them first" % len(hi),
                          "open_high": [{"id": i["id"], "location": i["location"], "issue": i["issue"]} for i in hi]}))
        return 2
    missing = [f for f in args.files if not os.path.isfile(f)]
    if missing:
        print(json.dumps({"exported": False, "reason": "missing files", "files": missing}))
        return 1
    flagged = []
    for f in args.files:
        try:
            with open(f, encoding="utf-8", errors="replace") as fh:
                m = SAFETY_WRITE_RE.search(fh.read())
            if m:
                flagged.append({"file": f, "instruction": m.group(1)})
        except OSError:
            pass
    if flagged:
        print(json.dumps({"exported": False, "blocked": True,
                          "reason": "deliverable contains safety-instruction calls; safety logic is never exported by Rungstone",
                          "files": flagged}))
        return 2

    stamp = _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
    root = os.path.dirname(d)
    out = os.path.join(root, args.out, stamp)
    os.makedirs(out, exist_ok=True)
    rows = []
    for f in args.files:
        dst = os.path.join(out, os.path.basename(f))
        shutil.copy2(f, dst)
        rows.append((os.path.basename(f), state.sha256(dst)))
    q = state.queue(d)["items"]
    proj = state.load(d, "project.json", {})
    vr = state.load(d, "verify_results.json", {}) or {}
    deps = state.load(d, "dependencies.json", {}) or {}
    L = ["# Rungstone export %s" % stamp, "",
         "Project: %s" % proj.get("name"), "",
         "These files are drafts generated by Rungstone and reviewed by the engineer. Import them into the vendor",
         "IDE, compile, and test offline. They are not for direct download to a running controller.", "",
         "**%s**" % NOT_FOR_PRODUCTION, "",
         "## Files", "", "| File | sha256 |", "|---|---|"]
    L += ["| %s | `%s` |" % r for r in rows]
    srcs = proj.get("sources") or []
    L += ["", "## Based on", ""]
    L += ["| %s | %s | `%s` |" % (x.get("path"), x.get("format") or "", x.get("sha256")) for x in srcs] if srcs else \
        ["Source files were not recorded in project.json (state.py source)."]
    if srcs:
        L[-len(srcs):-len(srcs)] = ["| Source | Format | sha256 |", "|---|---|---|"]
    if proj.get("target"):
        L += ["", "Target: %s" % proj["target"]]
    L += ["", "## Review decisions", "", "| ID | Risk | Status | Location | Issue | Resolution |", "|---|---|---|---|---|---|"]
    for i in q:
        L.append("| %s | %s | %s | %s | %s | %s |" % (i["id"], i["risk"], i["status"], i.get("location", ""),
                                                     i.get("issue", "").replace("|", "/"), (i.get("resolution") or "").replace("|", "/")))
    open_rest = [i for i in q if i["status"] == "open"]
    if open_rest:
        L += ["", "**Open medium/low items: %d** (export allowed; resolve before commissioning)." % len(open_rest)]
    runs = vr.get("runs") or vr.get("scenarios") or []
    L += ["", "## Verification", "", "Label: **%s**" % state.LABEL,
          "Scenario results recorded: %d" % (len(runs) if isinstance(runs, list) else 0) if runs else
          "No simulation results recorded: behavior was NOT verified."]
    excl = deps.get("excluded_safety") or []
    if excl:
        L += ["", "## Safety logic excluded (not exported)", ""] + ["- %s (%s): %s" % (e.get("name"), e.get("kind"), e.get("reason")) for e in excl]
    with open(os.path.join(out, "MANIFEST.md"), "w", encoding="utf-8") as fh:
        fh.write("\n".join(L) + "\n")
    state.log(d, "export", "%d file(s) -> %s" % (len(rows), os.path.relpath(out, root)))
    print(json.dumps({"exported": True, "folder": out, "files": [r[0] for r in rows], "open_medium_low": len(open_rest)}))
    return 0


if __name__ == "__main__":
    sys.exit(main())

SHA-256: 0a84533551a4b5d4c3b41175640e9368e1dd3936fb8feab675ec160b6cf8032f