From 9956139d5c42367763ed71e9aab32e6ab5181a99 Mon Sep 17 00:00:00 2001 From: Thomas Walker Lynch Date: Fri, 19 Sep 2025 00:19:53 -0700 Subject: [PATCH] pulling the staging code out to its own directory --- developer/source/StageHand/Planner.py | 533 ++++++++++++++++++ .../source/StageHand/deprecated/.githolder | 0 .../{DNS => StageHand/deprecated}/Planner.py | 0 .../source/StageHand/deprecated/Stage.py | 175 ++++++ .../source/StageHand/deprecated/executor.py | 359 ++++++++++++ .../{DNS => StageHand}/deprecated/stage_ls.py | 0 .../etc/nftables.d/10-block-IPv6.nft | 0 .../etc/nftables.d/20-SUBU-ports.nft | 0 .../etc/systemd/system/unbound@.service | 0 .../stage_orig/etc/unbound/unbound-US.conf | 0 .../stage_orig/etc/unbound/unbound-x6.conf | 0 .../stage_orig/usr/local/sbin/DNS_status.sh | 0 .../deprecated/stage_show_plan.py | 0 developer/source/StageHand/executor.py | 367 ++++++++++++ .../executor.py => StageHand/executor_2.py} | 1 + .../source/StageHand/scratchpad/.githolder | 0 .../stage_test_0/DNS/unbound.conf.py | 13 + .../stage_test_0/unbound_conf.py | 0 .../StageHand/stage_test_0/web/site_conf.py | 12 + .../{DNS => StageHand}/stagehand_filter.py | 0 20 files changed, 1460 insertions(+) create mode 100644 developer/source/StageHand/Planner.py create mode 100644 developer/source/StageHand/deprecated/.githolder rename developer/source/{DNS => StageHand/deprecated}/Planner.py (100%) create mode 100644 developer/source/StageHand/deprecated/Stage.py create mode 100755 developer/source/StageHand/deprecated/executor.py rename developer/source/{DNS => StageHand}/deprecated/stage_ls.py (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/etc/nftables.d/10-block-IPv6.nft (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/etc/nftables.d/20-SUBU-ports.nft (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/etc/systemd/system/unbound@.service (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/etc/unbound/unbound-US.conf (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/etc/unbound/unbound-x6.conf (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_orig/usr/local/sbin/DNS_status.sh (100%) rename developer/source/{DNS => StageHand}/deprecated/stage_show_plan.py (100%) create mode 100644 developer/source/StageHand/executor.py rename developer/source/{DNS/executor.py => StageHand/executor_2.py} (99%) mode change 100755 => 100644 create mode 100644 developer/source/StageHand/scratchpad/.githolder create mode 100644 developer/source/StageHand/stage_test_0/DNS/unbound.conf.py rename developer/source/{DNS => StageHand}/stage_test_0/unbound_conf.py (100%) create mode 100644 developer/source/StageHand/stage_test_0/web/site_conf.py rename developer/source/{DNS => StageHand}/stagehand_filter.py (100%) diff --git a/developer/source/StageHand/Planner.py b/developer/source/StageHand/Planner.py new file mode 100644 index 0000000..b5f4bac --- /dev/null +++ b/developer/source/StageHand/Planner.py @@ -0,0 +1,533 @@ +#!/usr/bin/env -S python3 -B +""" +Planner.py — plan builder for staged configuration (UNPRIVILEGED). + +Given: runner-side provenance (PlanProvenance) and optional defaults (WriteFileMeta). +Does: expose Planner whose command methods (copy/displace/delete) build Command entries, + resolving arguments with precedence: kwarg > per-call WriteFileMeta > planner default + (and for filename, fallback to provenance-derived basename). On any argument error, + the Command is returned with errors and NOT appended to the Journal. +Returns: Journal (model only; dict in/out) via planner.journal(). +""" + +from __future__ import annotations + +# no bytecode anywhere (works under sudo/root shells too) +import sys ,os +sys.dont_write_bytecode = True +os.environ.setdefault("PYTHONDONTWRITEBYTECODE" ,"1") + +from pathlib import Path +import getpass + + +# ===== Utilities ===== + +def norm_perm(value: int|str)-> tuple[int,str]|None: + "Given int or 3/4-char octal string (optionally 0o-prefixed). Does validate/normalize. Returns (int,'%04o') or None." + if isinstance(value ,int): + if 0 <= value <= 0o7777: + return value ,f"{value:04o}" + return None + if isinstance(value ,str): + s = value.strip().lower() + if s.startswith("0o"): + try: + v = int(s ,8) + return v ,f"{v:04o}" + except Exception: + return None + if len(s) in (3 ,4) and all(ch in "01234567" for ch in s): + try: + v = int(s ,8) + return v ,f"{v:04o}" + except Exception: + return None + return None + +def is_abs_dpath(dpath_str: str|None)-> bool: + "Given path string. Does quick abs dir check. Returns bool." + return isinstance(dpath_str ,str) and dpath_str.startswith("/") and "\x00" not in dpath_str + +def norm_abs_dpath_str(value: str|Path|None)-> str|None: + "Given str/Path/None. Does normalize absolute dir path string. Returns str or None." + if value is None: return None + s = value.as_posix() if isinstance(value ,Path) else str(value) + return s if is_abs_dpath(s) else None + +def norm_fname_or_none(value: str|None)-> str|None: + "Given candidate filename or None. Does validate bare filename. Returns str or None." + if value is None: return None + s = str(value) + if not s: return None + if "/" in s or s in ("." ,"..") or "\x00" in s: return None + return s + +def norm_nonempty_owner(value: str|None)-> str|None: + "Given owner string or None. Does minimally validate (non-empty). Returns str or None." + if value is None: return None + s = str(value).strip() + return s if s else None + +def parse_mode(value: int|str|None)-> tuple[int|None ,str|None]: + "Given int/str/None. Does normalize via norm_perm. Returns (int,'%04o') or (None,None)." + if value is None: return None ,None + r = norm_perm(value) + return r if r is not None else (None ,None) + +def norm_content_bytes(value: bytes|str|None)-> bytes|None: + "Given bytes/str/None. Does normalize to UTF-8 bytes or None. Returns bytes|None." + if value is None: return None + if isinstance(value ,bytes): return value + return value.encode("utf-8") + +def norm_dpath_str(value: str|Path|None)-> str|None: + "Given str/Path/None. Does minimal sanitize; allows relative. Returns str or None." + if value is None: return None + s = value.as_posix() if isinstance(value ,Path) else str(value) + if not s or "\x00" in s: return None + return s + + +# ===== Wire-ready model types (no CBOR here) ===== + +class Command: + """ + Command — a single planned operation. + + Given name_str ('copy'|'displace'|'delete'), optional arg_dict, optional errors_list. + Does hold op name, own a fresh arg_dict, collect per-entry errors. + Returns dictionary via as_dictionary(). + """ + __slots__ = ("name_str" ,"arg_dict" ,"errors_list") + + def __init__(self ,name_str: str ,arg_dict: dict|None=None ,errors_list: list[str]|None=None)-> None: + self.name_str = name_str + self.arg_dict = dict(arg_dict) if arg_dict is not None else {} + self.errors_list = list(errors_list) if errors_list is not None else [] + + def add_error(self ,msg_str: str)-> None: + self.errors_list.append(msg_str) + + def as_dictionary(self)-> dict: + return { + "op": self.name_str + ,"arg_dict": dict(self.arg_dict) + ,"errors_list": list(self.errors_list) + } + + def print(self, *, index: int|None=None, file=None)-> None: + """ + Given: optional index for numbering and optional file-like (defaults to stdout). + Does: print a compact, human-readable one-line summary of this command; prints any errors indented below. + Returns: None. + """ + if file is None: + import sys as _sys + file = _sys.stdout + + op = self.name_str + ad = self.arg_dict or {} + + # Compose destination path for display + d = ad.get("write_file_dpath_str") or "" + f = ad.get("write_file_fname") or "" + try: + from pathlib import Path as _Path + dst = (_Path(d)/f).as_posix() if d and f and "/" not in f else "?" + except Exception: + dst = "?" + + # Numbering prefix + prefix = f"{index:02d}. " if index is not None else "" + + if op == "copy": + mode = ad.get("mode_int") + owner = ad.get("owner_name") + size = len(ad.get("content_bytes") or b"") + line = f"{prefix}copy -> {dst} mode {mode:04o} owner {owner} bytes {size}" + elif op == "displace": + line = f"{prefix}displace -> {dst}" + elif op == "delete": + line = f"{prefix}delete -> {dst}" + else: + line = f"{prefix}?op? -> {dst}" + + print(line, file=file) + + # Print any per-entry errors underneath + for err in self.errors_list: + print(f" ! {err}", file=file) + + +class Journal: + """ + Journal — ordered list of Command plus provenance metadata (model only; no CBOR). + + Given optional plan_dict in wire shape (for reconstruction). + Does manage meta, append commands, expose entries, and pack to dict. + Returns dict via as_dictionary(). + """ + __slots__ = ("meta_dict" ,"command_list") + + def __init__(self ,plan_dict: dict|None=None)-> None: + self.meta_dict = {} + self.command_list = [] + if plan_dict is not None: + self._init_from_dict(plan_dict) + + def _init_from_dict(self ,plan_dict: dict)-> None: + if not isinstance(plan_dict ,dict): + raise ValueError("plan_dict must be a dict") + meta = dict(plan_dict.get("meta_dict") or {}) + entries = plan_dict.get("entries_list") or [] + self.meta_dict.update(meta) + for e in entries: + if not isinstance(e ,dict): + continue + op = e.get("op") or "?" + args = e.get("arg_dict") or {} + errs = e.get("errors_list") or [] + self.command_list.append(Command(name_str=op ,arg_dict=dict(args) ,errors_list=list(errs))) + + def set_meta(self ,**kv)-> None: + self.meta_dict.update(kv) + + def append(self ,cmd: Command)-> None: + self.command_list.append(cmd) + + def entries_list(self)-> list[dict]: + return [c.as_dictionary() for c in self.command_list] + + def as_dictionary(self)-> dict: + return { + "version_int": 1 + ,"meta_dict": dict(self.meta_dict) + ,"entries_list": self.entries_list() + } + + def print(self, *, index_start: int = 1, file=None) -> None: + """ + Given: optional starting index and optional file-like (defaults to stdout). + Does: print each Command on a single line via Command.print(), numbered. + Returns: None. + """ + if file is None: + import sys as _sys + file = _sys.stdout + + if not self.command_list: + print("(plan is empty)", file=file) + return + + for i, cmd in enumerate(self.command_list, start=index_start): + cmd.print(index=i, file=file) + +# ===== Runner-provided provenance ===== + +# Planner.py +class PlanProvenance: + """ + Runner-provided, read-only provenance for a single config script. + """ + __slots__ = ("stage_root_dpath","config_abs_fpath","config_rel_fpath", + "read_dir_dpath","read_fname","process_user") + + def __init__(self, *, stage_root: Path, config_path: Path): + import getpass + self.stage_root_dpath = stage_root.resolve() + self.config_abs_fpath = config_path.resolve() + try: + self.config_rel_fpath = self.config_abs_fpath.relative_to(self.stage_root_dpath) + except Exception: + self.config_rel_fpath = Path(self.config_abs_fpath.name) + + self.read_dir_dpath = self.config_abs_fpath.parent + + name = self.config_abs_fpath.name + if name.endswith(".stage.py"): + self.read_fname = name[:-len(".stage.py")] + elif name.endswith(".py"): + self.read_fname = name[:-3] + else: + self.read_fname = name + + # NEW: owner of the StageHand process + self.process_user = getpass.getuser() + + def print(self, *, file=None) -> None: + if file is None: + import sys as _sys + file = _sys.stdout + print(f"Stage root: {self.stage_root_dpath}", file=file) + print(f"Config (rel): {self.config_rel_fpath.as_posix()}", file=file) + print(f"Config (abs): {self.config_abs_fpath}", file=file) + print(f"Read dir: {self.read_dir_dpath}", file=file) + print(f"Read fname: {self.read_fname}", file=file) + print(f"Process user: {self.process_user}", file=file) # NEW + +# ===== Admin-facing defaults carrier ===== + +class WriteFileMeta: + """ + WriteFileMeta — per-call or planner-default write-file attributes. + + Given dpath (abs str/Path) ,fname (bare name or None) ,owner (str) + ,mode (int|'0644') ,content (bytes|str|None). + Does normalize into fields (may remain None if absent/invalid). + Returns object suitable for providing defaults to Planner methods. + """ + __slots__ = ("dpath_str" ,"fname" ,"owner_name_str" ,"mode_int" ,"mode_octal_str" ,"content_bytes") + + def __init__(self + ,* + ,dpath="/" + ,fname=None # None → let Planner/provenance choose + ,owner="root" + ,mode=0o444 + ,content=None + ): + self.dpath_str = norm_dpath_str(dpath) + self.fname = norm_fname_or_none(fname) # '.' no longer special → None + self.owner_name_str = norm_nonempty_owner(owner) # '.' rejected → None + self.mode_int, self.mode_octal_str = parse_mode(mode) + self.content_bytes = norm_content_bytes(content) + + def print(self, *, label: str | None = None, file=None) -> None: + """ + Given: optional label and optional file-like (defaults to stdout). + Does: print a single-line summary of defaults/overrides. + Returns: None. + """ + if file is None: + import sys as _sys + file = _sys.stdout + + dpath = self.dpath_str or "?" + fname = self.fname or "?" + owner = self.owner_name_str or "?" + mode_str = f"{self.mode_int:04o}" if isinstance(self.mode_int, int) else (self.mode_octal_str or "?") + size = len(self.content_bytes) if isinstance(self.content_bytes, (bytes, bytearray)) else 0 + prefix = (label + ": ") if label else "" + print(f"{prefix}dpath={dpath} fname={fname} owner={owner} mode={mode_str} bytes={size}", file=file) + + +# ===== Planner ===== + +class Planner: + """ + Planner — constructs a Journal of Commands from config scripts. + + Given provenance (PlanProvenance) and optional default WriteFileMeta. + Does resolve command parameters by precedence: kwarg > per-call WriteFileMeta > planner default, + with a final filename fallback to provenance basename if still missing. + On any argument error, returns the Command with errors and DOES NOT append it to Journal. + Returns live Journal via journal(). + """ + __slots__ = ("_prov" ,"_defaults" ,"_journal") + + def __init__(self ,provenance: PlanProvenance ,defaults: WriteFileMeta|None=None)-> None: + self._prov = provenance + self._defaults = defaults if defaults is not None else WriteFileMeta( + dpath="/" + ,fname=provenance.read_fname + ,owner="root" + ,mode=0o444 + ,content=None + ) + self._journal = Journal() + self._journal.set_meta( + stage_root_dpath_str=str(self._prov.stage_root_dpath) + ,config_rel_fpath_str=self._prov.config_rel_fpath.as_posix() + ) + + # --- defaults management / access --- + + # in Planner.py, inside class Planner + def set_provenance(self, prov: PlanProvenance) -> None: + """Switch the current provenance used for fallbacks & per-command provenance tagging.""" + self._prov = prov + + def set_defaults(self ,defaults: WriteFileMeta)-> None: + "Given WriteFileMeta. Does replace planner defaults. Returns None." + self._defaults = defaults + + def defaults(self)-> WriteFileMeta: + "Given n/a. Does return current WriteFileMeta defaults. Returns WriteFileMeta." + return self._defaults + + def journal(self)-> Journal: + "Given n/a. Returns Journal reference (live, still being modified here)." + return self._journal + + # --- resolution helpers --- + + def _pick(self ,kw ,meta_attr ,default_attr): + "Given three sources. Does pick first non-None. Returns value or None." + return kw if kw is not None else (meta_attr if meta_attr is not None else default_attr) + +# inside Planner + +from pathlib import Path +from posixpath import normpath as _normposix + + def _resolve_write_file(self, wfm, dpath, fname) -> tuple[str|None, str|None]: + # Normalize explicit kwargs (keep None as sentinel) + dpath_str = norm_dpath_str(dpath) if dpath is not None else None + if fname is not None and fname != ".": + fname = norm_fname_or_none(fname) + + # Precedence: kwarg > per-call meta > planner default + dpath_val = self._pick(dpath_str, (wfm.dpath_str if wfm else None), self._defaults.dpath_str) + fname_val = self._pick(fname, (wfm.fname if wfm else None), self._defaults.fname) + + # Final fallback for filename: "." or None → derive from config name + if fname_val == "." or fname_val is None: + fname_val = self._prov.read_fname + + # Anchor relative dpaths to the *process working directory* (CWD), then normalize. + if dpath_val is not None: + if is_abs_dpath(dpath_val): + # Normalize absolute path for pretty/consistency + try: + dpath_val = Path(dpath_val).resolve().as_posix() + except Exception: + dpath_val = _normposix(str(dpath_val)) + else: + base = Path.cwd() + try: + dpath_val = (base / dpath_val).resolve().as_posix() + except Exception: + dpath_val = _normposix((base / dpath_val).as_posix()) + + return dpath_val, fname_val + + def _resolve_owner_mode_content(self + ,wfm: WriteFileMeta|None + ,owner: str|None + ,mode: int|str|None + ,content: bytes|str|None + )-> tuple[str|None ,tuple[int|None ,str|None] ,bytes|None]: + owner_norm = norm_nonempty_owner(owner) if owner is not None else None + mode_norm = parse_mode(mode) if mode is not None else (None ,None) + content_b = norm_content_bytes(content) if content is not None else None + + owner_v = self._pick(owner_norm, (wfm.owner_name_str if wfm else None), self._defaults.owner_name_str) + mode_v = (mode_norm if mode_norm != (None ,None) else + ((wfm.mode_int ,wfm.mode_octal_str) if wfm else (self._defaults.mode_int ,self._defaults.mode_octal_str))) + content_v = self._pick(content_b ,(wfm.content_bytes if wfm else None) ,self._defaults.content_bytes) + return owner_v ,mode_v ,content_v + + def print(self, *, show_journal: bool = True, file=None) -> None: + """ + Given: flags (show_journal) and optional file-like (defaults to stdout). + Does: print provenance, defaults, and optionally the journal via delegation. + Returns: None. + """ + if file is None: + import sys as _sys + file = _sys.stdout + + print("== Provenance ==", file=file) + self._prov.print(file=file) + + print("\n== Defaults ==", file=file) + self._defaults.print(label="defaults", file=file) + + if show_journal: + entries = getattr(self._journal, "command_list", []) + n_total = len(entries) + n_copy = sum(1 for c in entries if getattr(c, "name_str", None) == "copy") + n_disp = sum(1 for c in entries if getattr(c, "name_str", None) == "displace") + n_del = sum(1 for c in entries if getattr(c, "name_str", None) == "delete") + + print("\n== Journal ==", file=file) + print(f"entries: {n_total} copy:{n_copy} displace:{n_disp} delete:{n_del}", file=file) + if n_total: + self._journal.print(index_start=1, file=file) + else: + print("(plan is empty)", file=file) + + # --- Command builders (first arg may be WriteFileMeta) --- + + def copy(self + ,wfm: WriteFileMeta|None=None + ,* + ,write_file_dpath: str|Path|None=None + ,write_file_fname: str|None=None + ,owner: str|None=None + ,mode: int|str|None=None + ,content: bytes|str|None=None + )-> Command: + """ + Given optional WriteFileMeta plus keyword overrides. + Does build a 'copy' command; on any argument error the command is returned with errors and NOT appended. + Returns Command. + """ + cmd = Command("copy") + dpath ,fname = self._resolve_write_file(wfm ,write_file_dpath ,write_file_fname) + owner_v ,(mode_int ,mode_oct) ,content_b = self._resolve_owner_mode_content(wfm ,owner ,mode ,content) + + # well-formed checks + if not is_abs_dpath(dpath): cmd.add_error("write_file_dpath must be absolute") + if norm_fname_or_none(fname) is None: cmd.add_error("write_file_fname must be a bare filename") + if not owner_v: cmd.add_error("owner must be non-empty") + if (mode_int ,mode_oct) == (None ,None): + cmd.add_error("mode must be int <= 0o7777 or 3/4-digit octal string") + if content_b is None: + cmd.add_error("content is required for copy() (bytes or str)") + + cmd.arg_dict.update({ + "write_file_dpath_str": dpath, + "write_file_fname": fname, # was write_file_fname + "owner_name": owner_v, # was owner_name_str + "mode_int": mode_int, + "mode_octal_str": mode_oct, + "content_bytes": content_b, + "provenance_config_rel_fpath_str": self._prov.config_rel_fpath.as_posix(), + }) + + if not cmd.errors_list: + self._journal.append(cmd) + return cmd + + def displace(self + ,wfm: WriteFileMeta|None=None + ,* + ,write_file_dpath: str|Path|None=None + ,write_file_fname: str|None=None + )-> Command: + "Given optional WriteFileMeta plus overrides. Does build 'displace' entry or return errors. Returns Command." + cmd = Command("displace") + dpath ,fname = self._resolve_write_file(wfm ,write_file_dpath ,write_file_fname) + if not is_abs_dpath(dpath): cmd.add_error("write_file_dpath must be absolute") + if norm_fname_or_none(fname) is None: cmd.add_error("write_file_fname must be a bare filename") + cmd.arg_dict.update({ + "write_file_dpath_str": dpath, + "write_file_fname": fname, + }) + if not cmd.errors_list: + self._journal.append(cmd) + return cmd + + def delete(self + ,wfm: WriteFileMeta|None=None + ,* + ,write_file_dpath: str|Path|None=None + ,write_file_fname: str|None=None + )-> Command: + "Given optional WriteFileMeta plus overrides. Does build 'delete' entry or return errors. Returns Command." + cmd = Command("delete") + dpath ,fname = self._resolve_write_file(wfm ,write_file_dpath ,write_file_fname) + if not is_abs_dpath(dpath): cmd.add_error("write_file_dpath must be absolute") + if norm_fname_or_none(fname) is None: cmd.add_error("write_file_fname must be a bare filename") + cmd.arg_dict.update({ + "write_file_dpath_str": dpath, + "write_file_fname": fname, + }) + if not cmd.errors_list: + self._journal.append(cmd) + return cmd + + + diff --git a/developer/source/StageHand/deprecated/.githolder b/developer/source/StageHand/deprecated/.githolder new file mode 100644 index 0000000..e69de29 diff --git a/developer/source/DNS/Planner.py b/developer/source/StageHand/deprecated/Planner.py similarity index 100% rename from developer/source/DNS/Planner.py rename to developer/source/StageHand/deprecated/Planner.py diff --git a/developer/source/StageHand/deprecated/Stage.py b/developer/source/StageHand/deprecated/Stage.py new file mode 100644 index 0000000..5cb0ba2 --- /dev/null +++ b/developer/source/StageHand/deprecated/Stage.py @@ -0,0 +1,175 @@ +#!/usr/bin/env -S python3 -B +""" +Stage.py — planner runtime for staged config programs (UNPRIVILEGED). + +Config usage: + import Stage + + Stage.init( + write_file_name="." + , write_dpath="/etc/unbound" + , write_file_owner_name="root" + , write_file_permissions=0o644 # or "0644" + , read_file_contents=b"...bytes..."# bytes preferred; str is utf-8 encoded + ) + Stage.displace() + Stage.copy() + # Stage.delete() + +Notes: + - This module only RECORDS plan steps using native Python values (ints/bytes/str). + - The outer tool CBOR-encodes the accumulated plan AFTER all configs run. +""" + +from __future__ import annotations +import sys ,os +sys.dont_write_bytecode = True +os.environ.setdefault("PYTHONDONTWRITEBYTECODE" ,"1") + +from dataclasses import dataclass ,field +from pathlib import Path +from typing import Any + +# ---------- helpers ---------- + +def _norm_perm(value: int|str)-> tuple[int,str]|None: + "Given: an int or a 4-char octal string. Does: validate/normalize to (int,'%04o'). Returns: tuple or None." + if isinstance(value ,int): + if 0 <= value <= 0o7777: + return value ,f"{value:04o}" + return None + if isinstance(value ,str): + s = value.strip() + if len(s)==4 and all(ch in "01234567" for ch in s): + try: + v = int(s ,8) + return v ,s + except Exception: + return None + return None + +@dataclass +class _Ctx: + "Information used by many entries in the plan, plan specific command defaults, i.e. the plan context." + read_rel_fpath: Path + stage_root_dpath: Path + defaults_map: dict[str,Any] = field(default_factory=dict) # this syntax gives each context instance a distinct dictionary. + +# ---------- planner singleton ---------- + +class _Planner: + "Given: staged config executions. Does: accumulate plan entries. Returns: plan map." + def __init__(self)-> None: + self._ctx: _Ctx|None = None + self._entries_list: list[dict[str,Any]] = [] + self._meta_map: dict[str,Any] = {} + + # ---- framework (called by outer tools) ---- + def _begin(self ,read_rel_fpath: Path ,stage_root_dpath: Path)-> None: + "Given: a config’s relative file path and stage root. Does: start context. Returns: None." + self._ctx = _Ctx(read_rel_fpath=read_rel_fpath ,stage_root_dpath=stage_root_dpath) + + def _end(self)-> None: + "Given: active context. Does: end it. Returns: None." + self._ctx = None + + def _reset(self)-> None: + "Given: n/a. Does: clear meta and entries. Returns: None." + self._entries_list.clear() + self._meta_map.clear() + self._ctx = None + + # ---- exported for outer tools ---- + def plan_entries(self)-> list[dict[str,Any]]: + "Given: n/a. Does: return a shallow copy of current entries. Returns: list[dict]." + return list(self._entries_list) + + def set_meta(self ,**kv)-> None: + "Given: keyword meta. Does: merge into meta_map. Returns: None." + self._meta_map.update(kv) + + def plan_object(self)-> dict[str,Any]: + "Packages a self-contained plan map ready for CBOR encoding. + Given: accumulated meta/entries. Does: freeze a copy and stamp a version. Returns: dict. + " + return { + "version_int": 1 + ,"meta_map": dict(self._meta_map) + ,"entries_list": list(self._entries_list) + } + + # ---- config API ---- + def init( + self + ,write_file_name: str + ,write_dpath: str + ,write_file_owner_name: str + ,write_file_permissions: int|str + ,read_file_contents: bytes|str|None=None + )-> None: + """ + Given: write filename ('.' → basename of config), destination dir path, owner name, + permissions (int or '0644'), and optional read content (bytes or str). + Does: store per-config defaults used by subsequent Stage.* calls. + Returns: None. + """ + if self._ctx is None: + raise RuntimeError("Stage.init used without active context") + fname = self._ctx.read_rel_fpath.name if write_file_name == "." else write_file_name + if isinstance(read_file_contents ,str): + content_bytes = read_file_contents.encode("utf-8") + else: + content_bytes = read_file_contents + perm_norm = _norm_perm(write_file_permissions) + if perm_norm is None: + mode_int ,mode_octal_str = None ,None + else: + mode_int ,mode_octal_str = perm_norm + self._ctx.defaults_map = { + "dst_fname": fname + ,"dst_dpath": write_dpath + ,"owner_name": write_file_owner_name + ,"mode_int": mode_int + ,"mode_octal_str": mode_octal_str + ,"content_bytes": content_bytes + } + + def _require_defaults(self)-> dict[str,Any]: + "Given: current ctx. Does: ensure Stage.init ran. Returns: defaults_map." + if self._ctx is None or not self._ctx.defaults_map: + raise RuntimeError("Stage.* called before Stage.init in this config") + return self._ctx.defaults_map + + def displace(self)-> None: + "Given: defaults. Does: append a displace op. Returns: None." + d = self._require_defaults() + self._entries_list.append({ + "op":"displace" + ,"dst_dpath": d["dst_dpath"] + ,"dst_fname": d["dst_fname"] + }) + + def copy(self)-> None: + "Given: defaults. Does: append a copy op. Returns: None." + d = self._require_defaults() + self._entries_list.append({ + "op":"copy" + ,"dst_dpath": d["dst_dpath"] + ,"dst_fname": d["dst_fname"] + ,"owner_name": d["owner_name"] + ,"mode_int": d["mode_int"] + ,"mode_octal_str": d["mode_octal_str"] + ,"content_bytes": d["content_bytes"] + }) + + def delete(self)-> None: + "Given: defaults. Does: append a delete op. Returns: None." + d = self._require_defaults() + self._entries_list.append({ + "op":"delete" + ,"dst_dpath": d["dst_dpath"] + ,"dst_fname": d["dst_fname"] + }) + +# exported singleton +Stage = _Planner() diff --git a/developer/source/StageHand/deprecated/executor.py b/developer/source/StageHand/deprecated/executor.py new file mode 100755 index 0000000..d8e3248 --- /dev/null +++ b/developer/source/StageHand/deprecated/executor.py @@ -0,0 +1,359 @@ +#!/usr/bin/env -S python3 -B +""" +executor.py — StageHand outer/inner executor (MVP; UNPRIVILEGED for now) + +Phase 0 (bootstrap): + - Ensure filter program exists (create default in CWD if --filter omitted) + - Validate --stage exists + - If --phase-0-then-stop: exit here (no scan ,no execution) + +Phase 1 (outer): + - Discover every file under --stage; acceptance filter decides which to include + - Execute each config’s configure(prov ,planner ,WriteFileMeta) into ONE Planner + - Optionally print the planner; optionally stop + +Phase 2 (inner shim in same program for now; no privilege yet): + - Encode plan to CBOR and hand to inner path + - Inner decodes to a Journal and can print it +""" + +from __future__ import annotations + +# no bytecode anywhere +import sys ,os +sys.dont_write_bytecode = True +os.environ.setdefault("PYTHONDONTWRITEBYTECODE" ,"1") + +from pathlib import Path +import argparse +import getpass +import tempfile +import runpy +import subprocess +import datetime as _dt +import stat + +# Local module: Planner.py (same directory) +from Planner import ( + Planner ,PlanProvenance ,WriteFileMeta ,Journal ,Command, +) + +# -------- default filter template (written to CWD when --filter not provided) -------- + +DEFAULT_FILTER_FILENAME = "stagehand_filter.py" + +DEFAULT_FILTER_SOURCE = """# StageHand acceptance filter (default template) +# Return True to include a config file ,False to skip it. +# You receive a PlanProvenance object named `prov`. +# +# prov fields commonly used here: +# prov.stage_root_dpath : Path → absolute path to the stage root +# prov.config_abs_fpath : Path → absolute path to the candidate file +# prov.config_rel_fpath : Path → path relative to the stage root +# prov.read_dir_dpath : Path → directory of the candidate file +# prov.read_fname : str → filename with trailing '.py' stripped (if present) +# +# Examples: +# +# 1) Accept everything (default behavior): +# def accept(prov): +# return True +# +# 2) Only accept configs in a 'dns/' namespace under the stage: +# def accept(prov): +# return prov.config_rel_fpath.as_posix().startswith("dns/") +# +# 3) Exclude editor backup files: +# def accept(prov): +# rel = prov.config_rel_fpath.as_posix() +# return not (rel.endswith("~") or rel.endswith(".swp")) +# +# 4) Only accept Python files + a few non-Python names: +# def accept(prov): +# name = prov.config_abs_fpath.name +# return name.endswith(".py") or name in {"hosts" ,"resolv.conf"} +# +# Choose ONE 'accept' definition. Below is the default: + +def accept(prov): + return True +""" + +# -------- utilities -------- + +def iso_utc_now_str() -> str: + return _dt.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ") + +def _ensure_filter_file(filter_arg: str|None) -> Path: + """ + If --filter is provided ,return that path (must exist). + Otherwise ,create ./stagehand_filter.py in the CWD if missing (writing a helpful template), + and return its path. + """ + if filter_arg: + p = Path(filter_arg) + if not p.is_file(): + raise RuntimeError(f"--filter file not found: {p}") + return p + + p = Path.cwd() / DEFAULT_FILTER_FILENAME + if not p.exists(): + try: + p.write_text(DEFAULT_FILTER_SOURCE ,encoding="utf-8") + print(f"(created default filter at {p})") + except Exception as e: + raise RuntimeError(f"failed to create default filter {p}: {e}") + return p + +def _load_accept_func(filter_path: Path): + env = runpy.run_path(str(filter_path)) + fn = env.get("accept") + if not callable(fn): + raise RuntimeError(f"{filter_path}: missing callable 'accept(prov)'") + return fn + +def _walk_all_files(stage_root: Path): + """ + Yield every file (regular or symlink) under stage_root recursively. + We do not follow symlinked directories to avoid cycles. + """ + root = stage_root.resolve() + for dirpath ,dirnames ,filenames in os.walk(root ,followlinks=False): + # prune symlinked dirs (files can still be symlinks) + dirnames[:] = [d for d in dirnames if not os.path.islink(os.path.join(dirpath ,d))] + for fname in filenames: + p = Path(dirpath ,fname) + try: + st = p.lstat() + if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): + yield p.resolve() + except Exception: + # unreadable/broken entries skipped + continue + +def find_config_paths(stage_root: Path ,accept_func) -> list[Path]: + out: list[tuple[int ,str ,Path]] = [] + root = stage_root.resolve() + for p in _walk_all_files(stage_root): + prov = PlanProvenance(stage_root=stage_root ,config_path=p) + try: + if accept_func(prov): + rel = p.resolve().relative_to(root) + out.append((len(rel.parts) ,rel.as_posix() ,p.resolve())) + except Exception as e: + raise RuntimeError(f"accept() failed on {prov.config_rel_fpath.as_posix()}: {e}") + out.sort(key=lambda t: (t[0] ,t[1])) # (depth ,name) + return [t[2] for t in out] + +# --- run all configs into ONE planner --- + +def _run_all_configs_into_single_planner(stage_root: Path ,cfgs: list[Path]) -> Planner: + """ + Create a single Planner and execute each config's configure(prov ,planner ,WriteFileMeta) + against it. Returns that single Planner containing the entire plan. + """ + # seed with synthetic provenance; we overwrite per config before execution + aggregate_prov = PlanProvenance(stage_root=stage_root ,config_path=stage_root / "(aggregate).py") + planner = Planner(provenance=aggregate_prov) + + for cfg in cfgs: + prov = PlanProvenance(stage_root=stage_root ,config_path=cfg) + planner.set_provenance(prov) + + env = runpy.run_path(str(cfg)) + fn = env.get("configure") + if not callable(fn): + raise RuntimeError(f"{cfg}: missing callable configure(prov ,planner ,WriteFileMeta)") + + fn(prov ,planner ,WriteFileMeta) + + # annotate meta once ,on the single planner's journal + j = planner.journal() + j.set_meta( + generator_prog_str="executor.py", + generated_at_utc_str=iso_utc_now_str(), + user_name_str=getpass.getuser(), + host_name_str=os.uname().nodename if hasattr(os ,"uname") else "unknown", + stage_root_dpath_str=str(stage_root.resolve()), + configs_list=[str(p.resolve().relative_to(stage_root.resolve())) for p in cfgs], + ) + return planner + +# ----- CBOR “matchbox” (simple wrapper kept local to executor) ----- + +def _plan_to_cbor_bytes(planner: Planner) -> bytes: + """Serialize a Planner's Journal to CBOR bytes.""" + try: + import cbor2 + except Exception as e: + raise RuntimeError(f"cbor2 is required: {e}") + plan_dict = planner.journal().as_dictionary() + return cbor2.dumps(plan_dict ,canonical=True) + +def _journal_from_cbor_bytes(data: bytes) -> Journal: + """Rebuild a Journal from CBOR bytes.""" + try: + import cbor2 + except Exception as e: + raise RuntimeError(f"cbor2 is required: {e}") + obj = cbor2.loads(data) + if not isinstance(obj ,dict): + raise ValueError("CBOR root must be a dict") + return Journal(plan_dict=obj) + +# -------- inner executor (phase 2) -------- + +def _inner_main(plan_path: Path ,phase2_print: bool ,phase2_then_stop: bool) -> int: + """Inner executor path: decode CBOR → Journal; optionally print; (apply TBD).""" + try: + data = Path(plan_path).read_bytes() + except Exception as e: + print(f"error: failed to read plan file: {e}" ,file=sys.stderr) + return 2 + + try: + journal = _journal_from_cbor_bytes(data) + except Exception as e: + print(f"error: failed to decode CBOR: {e}" ,file=sys.stderr) + return 2 + + if phase2_print: + journal.print() + + if phase2_then_stop: + return 0 + + # (Stage 3 apply would go here; omitted in MVP) + return 0 + +# -------- outer executor (phase 1 & handoff) -------- + +def _outer_main(stage_root: Path ,accept_func ,args) -> int: + if not stage_root.is_dir(): + print(f"error: --stage not a directory: {stage_root}" ,file=sys.stderr) + return 2 + + cfgs = find_config_paths(stage_root ,accept_func) + if not cfgs: + print("No configuration files found.") + return 0 + + try: + master = _run_all_configs_into_single_planner(stage_root ,cfgs) + except SystemExit: + raise + except Exception as e: + print(f"error: executing configs: {e}" ,file=sys.stderr) + return 2 + + if args.phase_1_print: + master.print() + + if args.phase_1_then_stop: + return 0 + + # Phase 2: encode CBOR and invoke inner path (same script ,--inner) + try: + cbor_bytes = _plan_to_cbor_bytes(master) + except Exception as e: + print(f"error: CBOR encode failed: {e}" ,file=sys.stderr) + return 2 + + with tempfile.NamedTemporaryFile(prefix="stagehand_plan_" ,suffix=".cbor" ,delete=False) as tf: + tf.write(cbor_bytes) + plan_path = tf.name + + try: + cmd = [ + sys.executable, + str(Path(__file__).resolve()), + "--inner", + "--plan" ,plan_path, + ] + if args.phase_2_print: + cmd.append("--phase-2-print") + if args.phase_2_then_stop: + cmd.append("--phase-2-then-stop") + + proc = subprocess.run(cmd) + return proc.returncode + finally: + try: + os.unlink(plan_path) + except Exception: + pass + +# -------- CLI -------- + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser( + prog="executor.py", + description="StageHand outer/inner executor (plan → CBOR → decode).", + ) + ap.add_argument("--stage" ,default="stage", + help="stage root directory (default: ./stage)") + ap.add_argument( + "--filter", + default="", + help=f"path to acceptance filter program exporting accept(prov) " + f"(default: ./{DEFAULT_FILTER_FILENAME}; created if missing)" + ) + ap.add_argument( + "--phase-0-then-stop", + action="store_true", + help="stop after arg checks & filter bootstrap (no stage scan)" + ) + + # Phase-1 (outer) controls + ap.add_argument("--phase-1-print" ,action="store_true" ,help="print master planner (phase 1)") + ap.add_argument("--phase-1-then-stop" ,action="store_true" ,help="stop after phase 1") + + # Phase-2 (inner) controls (outer forwards these to inner) + ap.add_argument("--phase-2-print" ,action="store_true" ,help="print decoded journal (phase 2)") + ap.add_argument("--phase-2-then-stop" ,action="store_true" ,help="stop after phase 2 decode") + + # Inner-only flags (not for users) + ap.add_argument("--inner" ,action="store_true" ,help=argparse.SUPPRESS) + ap.add_argument("--plan" ,default=None ,help=argparse.SUPPRESS) + + args = ap.parse_args(argv) + + # Inner path + if args.inner: + if not args.plan: + print("error: --inner requires --plan " ,file=sys.stderr) + return 2 + return _inner_main(Path(args.plan), + phase2_print=args.phase_2_print, + phase2_then_stop=args.phase_2_then_stop) + + # Phase 0: bootstrap & stop (no scan) + stage_root = Path(args.stage) + try: + filter_path = _ensure_filter_file(args.filter or None) + except Exception as e: + print(f"error: {e}" ,file=sys.stderr) + return 2 + + if not stage_root.exists(): + print(f"error: --stage not found: {stage_root}" ,file=sys.stderr) + return 2 + if not stage_root.is_dir(): + print(f"error: --stage is not a directory: {stage_root}" ,file=sys.stderr) + return 2 + + if args.phase_0_then_stop: + print(f"phase-0 OK: stage at {stage_root.resolve()} and filter at {filter_path}") + return 0 + + # Load acceptance function and proceed with outer + try: + accept_func = _load_accept_func(filter_path) + except Exception as e: + print(f"error: {e}" ,file=sys.stderr) + return 2 + + return _outer_main(stage_root ,accept_func ,args) + +if __name__ == "__main__": + sys.exit(main()) diff --git a/developer/source/DNS/deprecated/stage_ls.py b/developer/source/StageHand/deprecated/stage_ls.py similarity index 100% rename from developer/source/DNS/deprecated/stage_ls.py rename to developer/source/StageHand/deprecated/stage_ls.py diff --git a/developer/source/DNS/deprecated/stage_orig/etc/nftables.d/10-block-IPv6.nft b/developer/source/StageHand/deprecated/stage_orig/etc/nftables.d/10-block-IPv6.nft similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/etc/nftables.d/10-block-IPv6.nft rename to developer/source/StageHand/deprecated/stage_orig/etc/nftables.d/10-block-IPv6.nft diff --git a/developer/source/DNS/deprecated/stage_orig/etc/nftables.d/20-SUBU-ports.nft b/developer/source/StageHand/deprecated/stage_orig/etc/nftables.d/20-SUBU-ports.nft similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/etc/nftables.d/20-SUBU-ports.nft rename to developer/source/StageHand/deprecated/stage_orig/etc/nftables.d/20-SUBU-ports.nft diff --git a/developer/source/DNS/deprecated/stage_orig/etc/systemd/system/unbound@.service b/developer/source/StageHand/deprecated/stage_orig/etc/systemd/system/unbound@.service similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/etc/systemd/system/unbound@.service rename to developer/source/StageHand/deprecated/stage_orig/etc/systemd/system/unbound@.service diff --git a/developer/source/DNS/deprecated/stage_orig/etc/unbound/unbound-US.conf b/developer/source/StageHand/deprecated/stage_orig/etc/unbound/unbound-US.conf similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/etc/unbound/unbound-US.conf rename to developer/source/StageHand/deprecated/stage_orig/etc/unbound/unbound-US.conf diff --git a/developer/source/DNS/deprecated/stage_orig/etc/unbound/unbound-x6.conf b/developer/source/StageHand/deprecated/stage_orig/etc/unbound/unbound-x6.conf similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/etc/unbound/unbound-x6.conf rename to developer/source/StageHand/deprecated/stage_orig/etc/unbound/unbound-x6.conf diff --git a/developer/source/DNS/deprecated/stage_orig/usr/local/sbin/DNS_status.sh b/developer/source/StageHand/deprecated/stage_orig/usr/local/sbin/DNS_status.sh similarity index 100% rename from developer/source/DNS/deprecated/stage_orig/usr/local/sbin/DNS_status.sh rename to developer/source/StageHand/deprecated/stage_orig/usr/local/sbin/DNS_status.sh diff --git a/developer/source/DNS/deprecated/stage_show_plan.py b/developer/source/StageHand/deprecated/stage_show_plan.py similarity index 100% rename from developer/source/DNS/deprecated/stage_show_plan.py rename to developer/source/StageHand/deprecated/stage_show_plan.py diff --git a/developer/source/StageHand/executor.py b/developer/source/StageHand/executor.py new file mode 100644 index 0000000..454fe8e --- /dev/null +++ b/developer/source/StageHand/executor.py @@ -0,0 +1,367 @@ +#!/usr/bin/env -S python3 -B +""" +executor.py — StageHand outer/inner executor (MVP; UNPRIVILEGED for now) + +Phase 0 (bootstrap): + - Ensure filter program exists (create default in CWD if --filter omitted) + - Validate --stage exists + - If --phase-0-then-stop: exit here (no scan ,no execution) + +Phase 1 (outer): + - Discover every file under --stage; acceptance filter decides which to include + - Execute each config’s configure(prov ,planner ,WriteFileMeta) into ONE Planner + - Optionally print the planner; optionally stop + +Phase 2 (inner shim in same program for now; no privilege yet): + - Encode plan to CBOR and hand to inner path + - Inner decodes to a Journal and can print it +""" + +from __future__ import annotations + +# no bytecode anywhere +import sys ,os +sys.dont_write_bytecode = True +os.environ.setdefault("PYTHONDONTWRITEBYTECODE" ,"1") + +from pathlib import Path +import argparse +import getpass +import tempfile +import runpy +import subprocess +import datetime as _dt +import stat + +# Local module: Planner.py (same directory) +from Planner import ( + Planner + ,PlanProvenance + ,WriteFileMeta + ,Journal + ,Command +) + +# -------- default filter template (written to CWD when --filter not provided) -------- + +DEFAULT_FILTER_FILENAME = "stagehand_filter.py" + +DEFAULT_FILTER_SOURCE = """# StageHand acceptance filter (default template) +# Return True to include a config file ,False to skip it. +# You receive a PlanProvenance object named `prov`. +# +# prov fields commonly used here: +# prov.stage_root_dpath : Path → absolute path to the stage root +# prov.config_abs_fpath : Path → absolute path to the candidate file +# prov.config_rel_fpath : Path → path relative to the stage root +# prov.read_dir_dpath : Path → directory of the candidate file +# prov.read_fname : str → filename with trailing '.py' stripped (if present) +# +# Examples: +# +# 1) Accept everything (default behavior): +# def accept(prov): +# return True +# +# 2) Only accept configs in a 'dns/' namespace under the stage: +# def accept(prov): +# return prov.config_rel_fpath.as_posix().startswith("dns/") +# +# 3) Exclude editor backup files: +# def accept(prov): +# rel = prov.config_rel_fpath.as_posix() +# return not (rel.endswith("~") or rel.endswith(".swp")) +# +# 4) Only accept Python files + a few non-Python names: +# def accept(prov): +# name = prov.config_abs_fpath.name +# return name.endswith(".py") or name in {"hosts" ,"resolv.conf"} +# +# Choose ONE 'accept' definition. Below is the default: + +def accept(prov): + return True +""" + +# -------- utilities -------- + +def iso_utc_now_str()-> str: + return _dt.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ") + +def _ensure_filter_file(filter_arg: str|None)-> Path: + """ + If --filter is provided ,return that path (must exist). + Otherwise ,create ./stagehand_filter.py in the CWD if missing (writing a helpful template), + and return its path. + """ + if filter_arg: + p = Path(filter_arg) + if not p.is_file(): + raise RuntimeError(f"--filter file not found: {p}") + return p + + p = Path.cwd()/DEFAULT_FILTER_FILENAME + if not p.exists(): + try: + p.write_text(DEFAULT_FILTER_SOURCE ,encoding="utf-8") + print(f"(created default filter at {p})") + except Exception as e: + raise RuntimeError(f"failed to create default filter {p}: {e}") + return p + +def _load_accept_func(filter_path: Path): + env = runpy.run_path(str(filter_path)) + fn = env.get("accept") + if not callable(fn): + raise RuntimeError(f"{filter_path}: missing callable 'accept(prov)'") + return fn + +def _walk_all_files(stage_root: Path): + """ + Yield every file (regular or symlink) under stage_root recursively. + We do not follow symlinked directories to avoid cycles. + """ + root = stage_root.resolve() + for dirpath ,dirnames ,filenames in os.walk(root ,followlinks=False): + # prune symlinked dirs (files can still be symlinks) + dirnames[:] = [d for d in dirnames if not os.path.islink(os.path.join(dirpath ,d))] + for fname in filenames: + p = Path(dirpath ,fname) + try: + st = p.lstat() + if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode): + yield p.resolve() + except Exception: + # unreadable/broken entries skipped + continue + +def find_config_paths(stage_root: Path ,accept_func)-> list[Path]: + """ + Return files accepted by the Python acceptance function: accept(prov) → True/False. + Ordered breadth-first by depth ,then lexicographically by relative path. + """ + out: list[tuple[int ,str ,Path]] = [] + root = stage_root.resolve() + for p in _walk_all_files(stage_root): + prov = PlanProvenance(stage_root=stage_root ,config_path=p) + try: + if accept_func(prov): + rel = p.resolve().relative_to(root) + out.append((len(rel.parts) ,rel.as_posix() ,p.resolve())) + except Exception as e: + raise RuntimeError(f"accept() failed on {prov.config_rel_fpath.as_posix()}: {e}") + out.sort(key=lambda t: (t[0] ,t[1])) # (depth ,name) + return [t[2] for t in out] + +# --- run all configs into ONE planner --- + +def _run_all_configs_into_single_planner(stage_root: Path ,cfgs: list[Path])-> Planner: + """ + Create a single Planner and execute each config's configure(prov ,planner ,WriteFileMeta) + against it. Returns that single Planner containing the entire plan. + """ + # seed with synthetic provenance; we overwrite per config before execution + aggregate_prov = PlanProvenance(stage_root=stage_root ,config_path=stage_root/"(aggregate).py") + planner = Planner(provenance=aggregate_prov) + + for cfg in cfgs: + prov = PlanProvenance(stage_root=stage_root ,config_path=cfg) + planner.set_provenance(prov) + + env = runpy.run_path(str(cfg)) + fn = env.get("configure") + if not callable(fn): + raise RuntimeError(f"{cfg}: missing callable configure(prov ,planner ,WriteFileMeta)") + + fn(prov ,planner ,WriteFileMeta) + + # annotate meta once ,on the single planner's journal + j = planner.journal() + j.set_meta( + generator_prog_str="executor.py" + ,generated_at_utc_str=iso_utc_now_str() + ,user_name_str=getpass.getuser() + ,host_name_str=os.uname().nodename if hasattr(os ,"uname") else "unknown" + ,stage_root_dpath_str=str(stage_root.resolve()) + ,configs_list=[str(p.resolve().relative_to(stage_root.resolve())) for p in cfgs] + ) + return planner + +# ----- CBOR “matchbox” (simple wrapper kept local to executor) ----- + +def _plan_to_cbor_bytes(planner: Planner)-> bytes: + "Serialize a Planner's Journal to CBOR bytes." + try: + import cbor2 + except Exception as e: + raise RuntimeError(f"cbor2 is required: {e}") + plan_dict = planner.journal().as_dictionary() + return cbor2.dumps(plan_dict ,canonical=True) + +def _journal_from_cbor_bytes(data: bytes)-> Journal: + "Rebuild a Journal from CBOR bytes." + try: + import cbor2 + except Exception as e: + raise RuntimeError(f"cbor2 is required: {e}") + obj = cbor2.loads(data) + if not isinstance(obj ,dict): + raise ValueError("CBOR root must be a dict") + return Journal(plan_dict=obj) + +# -------- inner executor (phase 2) -------- + +def _inner_main(plan_path: Path ,phase2_print: bool ,phase2_then_stop: bool)-> int: + "Inner executor path: decode CBOR → Journal; optionally print; (apply TBD)." + try: + data = Path(plan_path).read_bytes() + except Exception as e: + print(f"error: failed to read plan file: {e}" ,file=sys.stderr) + return 2 + + try: + journal = _journal_from_cbor_bytes(data) + except Exception as e: + print(f"error: failed to decode CBOR: {e}" ,file=sys.stderr) + return 2 + + if phase2_print: + journal.print() + + if phase2_then_stop: + return 0 + + # (Stage 3 apply would go here; omitted in MVP) + return 0 + +# -------- outer executor (phase 1 & handoff) -------- + +def _outer_main(stage_root: Path ,accept_func ,args)-> int: + if not stage_root.is_dir(): + print(f"error: --stage not a directory: {stage_root}" ,file=sys.stderr) + return 2 + + cfgs = find_config_paths(stage_root ,accept_func) + if not cfgs: + print("No configuration files found.") + return 0 + + try: + master = _run_all_configs_into_single_planner(stage_root ,cfgs) + except SystemExit: + raise + except Exception as e: + print(f"error: executing configs: {e}" ,file=sys.stderr) + return 2 + + if args.phase_1_print: + master.print() + + if args.phase_1_then_stop: + return 0 + + # Phase 2: encode CBOR and invoke inner path (same script ,--inner) + try: + cbor_bytes = _plan_to_cbor_bytes(master) + except Exception as e: + print(f"error: CBOR encode failed: {e}" ,file=sys.stderr) + return 2 + + with tempfile.NamedTemporaryFile(prefix="stagehand_plan_" ,suffix=".cbor" ,delete=False) as tf: + tf.write(cbor_bytes) + plan_path = tf.name + + try: + cmd = [ + sys.executable + ,str(Path(__file__).resolve()) + ,"--inner" + ,"--plan" ,plan_path + ] + if args.phase_2_print: + cmd.append("--phase-2-print") + if args.phase_2_then_stop: + cmd.append("--phase-2-then-stop") + + proc = subprocess.run(cmd) + return proc.returncode + finally: + try: + os.unlink(plan_path) + except Exception: + pass + +# -------- CLI -------- + +def main(argv: list[str]|None=None)-> int: + ap = argparse.ArgumentParser( + prog="executor.py" + ,description="StageHand outer/inner executor (plan → CBOR → decode)." + ) + ap.add_argument("--stage" ,default="stage" + ,help="stage root directory (default: ./stage)") + ap.add_argument( + "--filter" + ,default="" + ,help=f"path to acceptance filter program exporting accept(prov) " + f"(default: ./{DEFAULT_FILTER_FILENAME}; created if missing)" + ) + ap.add_argument( + "--phase-0-then-stop" + ,action="store_true" + ,help="stop after arg checks & filter bootstrap (no stage scan)" + ) + + # Phase-1 (outer) controls + ap.add_argument("--phase-1-print" ,action="store_true" ,help="print master planner (phase 1)") + ap.add_argument("--phase-1-then-stop" ,action="store_true" ,help="stop after phase 1") + + # Phase-2 (inner) controls (outer forwards these to inner) + ap.add_argument("--phase-2-print" ,action="store_true" ,help="print decoded journal (phase 2)") + ap.add_argument("--phase-2-then-stop" ,action="store_true" ,help="stop after phase 2 decode") + + # Inner-only flags (not for users) + ap.add_argument("--inner" ,action="store_true" ,help=argparse.SUPPRESS) + ap.add_argument("--plan" ,default=None ,help=argparse.SUPPRESS) + + args = ap.parse_args(argv) + + # Inner path + if args.inner: + if not args.plan: + print("error: --inner requires --plan " ,file=sys.stderr) + return 2 + return _inner_main(Path(args.plan) + ,phase2_print=args.phase_2_print + ,phase2_then_stop=args.phase_2_then_stop) + + # Phase 0: bootstrap & stop (no scan) + stage_root = Path(args.stage) + try: + filter_path = _ensure_filter_file(args.filter or None) + except Exception as e: + print(f"error: {e}" ,file=sys.stderr) + return 2 + + if not stage_root.exists(): + print(f"error: --stage not found: {stage_root}" ,file=sys.stderr) + return 2 + if not stage_root.is_dir(): + print(f"error: --stage is not a directory: {stage_root}" ,file=sys.stderr) + return 2 + + if args.phase_0_then_stop: + print(f"phase-0 OK: stage at {stage_root.resolve()} and filter at {filter_path}") + return 0 + + # Load acceptance function and proceed with outer + try: + accept_func = _load_accept_func(filter_path) + except Exception as e: + print(f"error: {e}" ,file=sys.stderr) + return 2 + + return _outer_main(stage_root ,accept_func ,args) + +if __name__ == "__main__": + sys.exit(main()) diff --git a/developer/source/DNS/executor.py b/developer/source/StageHand/executor_2.py old mode 100755 new mode 100644 similarity index 99% rename from developer/source/DNS/executor.py rename to developer/source/StageHand/executor_2.py index 1690f49..ee13bdd --- a/developer/source/DNS/executor.py +++ b/developer/source/StageHand/executor_2.py @@ -1,3 +1,4 @@ + #!/usr/bin/env -S python3 -B """ executor.py — StageHand outer/inner executor (MVP; UNPRIVILEGED for now) diff --git a/developer/source/StageHand/scratchpad/.githolder b/developer/source/StageHand/scratchpad/.githolder new file mode 100644 index 0000000..e69de29 diff --git a/developer/source/StageHand/stage_test_0/DNS/unbound.conf.py b/developer/source/StageHand/stage_test_0/DNS/unbound.conf.py new file mode 100644 index 0000000..9a8fd8a --- /dev/null +++ b/developer/source/StageHand/stage_test_0/DNS/unbound.conf.py @@ -0,0 +1,13 @@ +# stage_test_0/DNS/unbound_conf.py + +def configure(prov, planner, WriteFileMeta): + # dpath is relative; it will be anchored to prov.read_dir_dpath, + # so this lands in .../stage_test_0/stage_test_0_out/dns + wfm = WriteFileMeta( + dpath="stage_test_0_out/net", + fname=prov.read_fname, # "unbound_conf" + owner=prov.process_user, # current process user + mode=0o444 + ) + planner.delete(wfm) + planner.copy(wfm, content="server:\n verbosity: 1\n") diff --git a/developer/source/DNS/stage_test_0/unbound_conf.py b/developer/source/StageHand/stage_test_0/unbound_conf.py similarity index 100% rename from developer/source/DNS/stage_test_0/unbound_conf.py rename to developer/source/StageHand/stage_test_0/unbound_conf.py diff --git a/developer/source/StageHand/stage_test_0/web/site_conf.py b/developer/source/StageHand/stage_test_0/web/site_conf.py new file mode 100644 index 0000000..21397c4 --- /dev/null +++ b/developer/source/StageHand/stage_test_0/web/site_conf.py @@ -0,0 +1,12 @@ +# stage_test_0/web/site_conf.py + +def configure(prov, planner, WriteFileMeta): + # This writes a faux web config to .../stage_test_0/stage_test_0_out/web/nginx.conf + wfm = WriteFileMeta( + dpath="stage_test_0_out/web", + fname="nginx.conf", # explicit override (not from prov) + owner=prov.process_user, + mode="0644" + ) + planner.displace(wfm) + planner.copy(wfm, content="events {}\nhttp { server { listen 8080; } }\n") diff --git a/developer/source/DNS/stagehand_filter.py b/developer/source/StageHand/stagehand_filter.py similarity index 100% rename from developer/source/DNS/stagehand_filter.py rename to developer/source/StageHand/stagehand_filter.py -- 2.20.1