Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SP Boucher Development Standard7# File : payload/standards/lib/spstd/common.py8# Module : Engine9# Repository : https://git.spboucher.ai/sp-development-standard10# Project Website : https://git.spboucher.ai/sp-development-standard11# Created : 2026-12-0212# Last Modified : 2026-12-0213#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Shared helpers of the SP Boucher development standard (Python 3.8+, standard library only)."""42import datetime43import fnmatch44import json45import os46import re47import subprocess48import sys4950HOME = os.path.expanduser("~")51LIB_DIR = os.path.dirname(os.path.abspath(__file__))52STD_DIR = os.environ.get("SP_STANDARD_DIR") or os.path.normpath(os.path.join(LIB_DIR, "..", ".."))53STATE_DIR = os.environ.get("SP_STATE_DIR") or os.path.join(HOME, ".claude", "state", "sp-standard")5455_cache = {}565758def version():59 try:60 with open(os.path.join(STD_DIR, "VERSION"), encoding="utf-8") as f:61 return f.read().strip()62 except OSError:63 return "unknown"646566def load_json(rel, default=None):67 """Load a JSON file of the standards directory (cached)."""68 if rel in _cache:69 return _cache[rel]70 try:71 with open(os.path.join(STD_DIR, rel), encoding="utf-8") as f:72 data = json.load(f)73 except (OSError, ValueError):74 if default is None:75 raise76 data = default77 _cache[rel] = data78 return data798081def identity():82 return load_json("identity.json")838485def git_config():86 return load_json("git-governance/config.json")878889def local_overrides():90 """Machine-local, never published overrides (restricted repositories, extra secret patterns)."""91 return load_json("local/overrides.json", default={})929394def run(cmd, cwd=None, timeout=30, env=None, stdin=None):95 """Run a command; never raises. Returns (returncode, stdout, stderr)."""96 try:97 p = subprocess.run(cmd, cwd=cwd, timeout=timeout, env=env, input=stdin,98 stdout=subprocess.PIPE, stderr=subprocess.PIPE)99 return p.returncode, p.stdout.decode("utf-8", "replace"), p.stderr.decode("utf-8", "replace")100 except subprocess.TimeoutExpired:101 return 124, "", "timeout after %ss: %s" % (timeout, " ".join(cmd[:4]))102 except OSError as e:103 return 127, "", str(e)104105106def git(args, cwd, timeout=30):107 return run(["git"] + list(args), cwd=cwd, timeout=timeout)108109110def git_out(args, cwd, timeout=30):111 rc, out, _ = git(args, cwd, timeout)112 return out.strip() if rc == 0 else ""113114115def git_root(path):116 d = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path))117 while d and not os.path.isdir(d):118 d = os.path.dirname(d)119 if not d:120 return None121 key = ("root", d)122 if key not in _cache:123 out = git_out(["rev-parse", "--show-toplevel"], d, 10)124 _cache[key] = os.path.realpath(out) if out else None125 return _cache[key]126127128MANIFESTS = ("package.json", "Cargo.toml", "pyproject.toml", "setup.py", "Package.swift", "go.mod", "build.gradle",129 "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "pom.xml", "composer.json", "Gemfile",130 "pubspec.yaml", "CMakeLists.txt", "Makefile", ".sp-standard.json", ".spb-source-governance.toml")131132133def project_root(path):134 """Git top-level if any, else the nearest ancestor holding a project manifest. Never $HOME or /."""135 r = git_root(path)136 if r:137 return r138 d = os.path.realpath(path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)))139 home = os.path.realpath(HOME)140 while d and d not in ("/", home):141 try:142 names = os.listdir(d)143 except OSError:144 names = []145 if any(m in names for m in MANIFESTS) or any(n.endswith(".xcodeproj") for n in names):146 return d147 d = os.path.dirname(d)148 return None149150151def in_ignored_root(path):152 if os.environ.get("SP_TEST_NO_IGNORED_ROOTS"):153 return False154 p = os.path.realpath(path)155 for r in load_json("source-header/exclusions.json").get("ignored_roots", []):156 r = os.path.realpath(os.path.expanduser(r))157 if p == r or p.startswith(r + os.sep):158 return True159 return False160161162# --------------------------------------------------------------------------- minimal TOML (v1 policy files)163def read_simple_toml(path):164 """Tiny reader for .spb-source-governance.toml: sections, strings, string arrays, numbers, booleans."""165 data, section = {}, None166 try:167 with open(path, encoding="utf-8") as f:168 text = f.read()169 except OSError:170 return data171 for m in re.finditer(r'^\s*\[([A-Za-z0-9_.-]+)\]\s*$|^\s*([A-Za-z0-9_-]+)\s*=\s*(\[.*?\]|"(?:[^"\\]|\\.)*"|[^\n#]+)',172 text, re.M | re.S):173 if m.group(1):174 section = m.group(1)175 data.setdefault(section, {})176 continue177 key, raw = m.group(2), m.group(3).strip()178 if raw.startswith("["):179 val = [bytes(s, "utf-8").decode("unicode_escape", "replace") if "\\" in s else s180 for s in re.findall(r'"((?:[^"\\]|\\.)*)"', raw)]181 elif raw.startswith('"'):182 val = raw[1:-1].replace('\\"', '"').replace("\\\\", "\\")183 elif raw in ("true", "false"):184 val = raw == "true"185 else:186 val = raw187 (data[section] if section else data)[key] = val188 return data189190191def repo_policy(root):192 """Merged per-repository policy: .sp-standard.json (v2) over .spb-source-governance.toml (v1)."""193 key = ("policy", root)194 if key in _cache:195 return _cache[key]196 pol = {"v1": None, "v2": None}197 p1 = os.path.join(root, ".spb-source-governance.toml")198 if os.path.isfile(p1):199 pol["v1"] = read_simple_toml(p1)200 p2 = os.path.join(root, ".sp-standard.json")201 if os.path.isfile(p2):202 try:203 with open(p2, encoding="utf-8") as f:204 pol["v2"] = json.load(f)205 except (OSError, ValueError):206 pol["v2"] = {"_invalid": True}207 _cache[key] = pol208 return pol209210211# --------------------------------------------------------------------------- remotes212def sanitize_url(url):213 """Strip credentials embedded in a remote URL."""214 return re.sub(r"^([a-z+]+://)[^/@\s]+@", r"\1", url.strip())215216217def origin_info(root):218 """Describe the origin remote: kind in none|spbgit-public|spbgit-private|own|foreign."""219 info = {"raw": "", "kind": "none", "slug": "", "web": ""}220 if not root or not git_root(root):221 return info222 url = git_out(["remote", "get-url", "origin"], root, 10)223 if not url:224 return info225 cfg = git_config()226 host = cfg["repository"]["host"].rstrip("/")227 info["raw"] = sanitize_url(url)228 slug = re.sub(r"\.git/?$", "", url.rstrip("/")).split("/")[-1].split(":")[-1]229 info["slug"] = slug230 if "srv/git-private/" in url:231 info["kind"] = "spbgit-private"232 info["web"] = "Private repository (SPB Git)"233 local = os.environ.get("SP_GIT_LOCAL_BACKEND")234 # the forge keeps symlinks git-private/<n>.git -> git/<n>.git for repositories that were made public235 if local and os.path.islink(os.path.join(local, "srv/git-private", slug + ".git")):236 info["kind"], info["web"] = "spbgit-public", "%s/%s" % (host, slug)237 elif "srv/git/" in url or re.search(r"(^|[@/])git\.spboucher\.ai[:/]", url):238 info["kind"] = "spbgit-public"239 info["web"] = "%s/%s" % (host, slug)240 elif any(re.search(p, url) for p in cfg["remote"]["owned_remote_patterns"]):241 info["kind"] = "own"242 m = re.search(r"github\.com[:/]([^/]+)/([^/]+?)(\.git)?$", url)243 info["web"] = "https://github.com/%s/%s" % (m.group(1), m.group(2)) if m else "Private repository"244 else:245 info["kind"] = "foreign"246 m = re.search(r"(?:https?://|git@|ssh://(?:[^@/]+@)?)([^/:]+)[:/](.+?)(\.git)?/?$", sanitize_url(url))247 info["web"] = "https://%s/%s" % (m.group(1), m.group(2)) if m else info["raw"]248 return info249250251def ownership(root):252 """(status, reason) — status in owned | unknown | foreign | restricted.253254 Headers are stamped automatically only on positive evidence of SP Boucher ownership."""255 if not root:256 return "unknown", "no project root"257 key = ("own", root)258 if key in _cache:259 return _cache[key]260 res = _ownership(root)261 _cache[key] = res262 return res263264265def _ownership(root):266 own = identity()["identity"]["author"]267 pol = repo_policy(root)268 v2 = pol["v2"]269 if v2 is not None:270 if v2.get("headers") is False:271 return "restricted", ".sp-standard.json disables headers"272 if str(v2.get("owner", "")).lower() in ("third-party", "foreign", "other"):273 return "foreign", ".sp-standard.json declares a third-party owner"274 if str(v2.get("owner", "")).lower() in ("sp-boucher", "spboucher", "simon-pierre boucher"):275 return "owned", ".sp-standard.json"276 o = origin_info(root)277 restricted = set(local_overrides().get("restricted_repos", []))278 if o["slug"] and o["slug"] in restricted or os.path.basename(root) in restricted:279 return "restricted", "attribution of this repository is under review (local overrides)"280 v1 = pol["v1"]281 if v1 is not None:282 holder = (v1.get("copyright") or {}).get("holder", "")283 if v1.get("status") != "in-scope":284 return "restricted", "v1 policy status is %r" % v1.get("status")285 if own not in holder:286 return "restricted", "v1 policy does not assert Simon-Pierre Boucher as rights holder"287 return "owned", ".spb-source-governance.toml"288 if o["kind"] in ("spbgit-public", "spbgit-private", "own"):289 return "owned", "origin is %s" % (o["web"] or o["raw"])290 if o["kind"] == "foreign":291 return "foreign", "origin is a third-party remote (%s)" % o["web"]292 return "unknown", "no remote and no policy file yet (run `sp-git init`)"293294295def porcelain(root):296 """Paths reported by `git status --porcelain` (new name for renames, directories keep their trailing slash)."""297 rc, out, _ = git(["-c", "core.quotepath=off", "status", "--porcelain"], root, 30)298 if rc != 0:299 return []300 return [l[3:].split(" -> ")[-1].strip('"') for l in out.split("\n") if len(l) > 3]301302303def today():304 return datetime.date.today().isoformat()305306307def rel_to(path, root):308 return os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/")309310311def glob_match(rel, patterns):312 for p in patterns or []:313 if fnmatch.fnmatch(rel, p) or fnmatch.fnmatch(rel, p.rstrip("/*") + "/*") or rel == p.rstrip("/"):314 return True315 if p.endswith("/**") and rel.startswith(p[:-3].rstrip("/") + "/"):316 return True317 return False318319320def list_files(directory):321 """Files under a directory: tracked + untracked-not-ignored when in git, else a filtered walk."""322 directory = os.path.realpath(directory)323 if git_root(directory):324 rc, out, _ = run(["git", "ls-files", "-co", "--exclude-standard", "-z"], cwd=directory, timeout=60)325 if rc == 0:326 return [os.path.join(directory, f) for f in out.split("\0") if f and os.path.isfile(os.path.join(directory, f))]327 ex = load_json("source-header/exclusions.json")["dirs"]328 skip = set(sum(ex.values(), []))329 res = []330 for base, dirs, files in os.walk(directory):331 dirs[:] = [d for d in dirs if d not in skip and not d.startswith(".")]332 res.extend(os.path.join(base, f) for f in files)333 return res334335336def eprint(*a):337 print(*a, file=sys.stderr)338339340class RepoLock(object):341 """Per-repository advisory lock (mkdir based, stale after 10 minutes) to serialise commits and pushes."""342343 def __init__(self, root, name="sp-git"):344 gd = git_out(["rev-parse", "--absolute-git-dir"], root, 10) or os.path.join(root, ".git")345 self.path = os.path.join(gd, name + ".lock.d")346347 def __enter__(self):348 import time349 for _ in range(120):350 try:351 os.mkdir(self.path)352 return self353 except FileExistsError:354 try:355 if time.time() - os.path.getmtime(self.path) > 600:356 os.rmdir(self.path)357 continue358 except OSError:359 pass360 time.sleep(0.5)361 except OSError:362 return self363 raise SystemExit("sp-git: another commit/push is running in this repository (lock %s)" % self.path)364365 def __exit__(self, *a):366 try:367 os.rmdir(self.path)368 except OSError:369 pass370