Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : SP Boucher Source Governance9# File : spbheader/core.py10# Description : File-level engine: decide whether a file may carry a11# header, where it goes, render it, insert / update / remove12# it without touching anything else.13# Module : spbheader14# Repository : https://git.spboucher.ai/spb-source-governance15# Project Website : https://git.spboucher.ai16# Created : 2026-11-2117# Last Modified : 2026-11-2118#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author : Simon-Pierre Boucher24# Position : Professor of Finance25# Institution : Université du Québec en Outaouais (UQO)26# Department : Département des sciences administratives27# Organization : SP Boucher28#29# Website : https://spboucher.ai30# Git : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General : info@spboucher.ai37# Professional : contact@spboucher.ai38# Direct : simon@spboucher.ai39# Research : research@spboucher.ai40# Development : dev@spboucher.ai41# Support : support@spboucher.ai42# Security/Admin : admin@spboucher.ai43# Notifications : notifications@spboucher.ai44#45# Preferred Contact: dev@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification : Public70# Distribution : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License : None specified (no license file in this repository)84# Maintainer : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""File-level engine: decide whether a file may carry a header, where it goes,92render it, insert / update / remove it without touching anything else.9394Design rule: a change is always a pure splice. The new file is95``old[:a] + header + old[b:]`` where ``old[a:b]`` is nothing, one blank line,96a previous SP Boucher header, or a legacy identity block that was recognised97line by line. Bytes outside the splice are never re-encoded or re-wrapped.98"""99from __future__ import annotations100101import hashlib102import json103import re104import tomllib105from dataclasses import dataclass, field106from pathlib import Path107108ROOT = Path(__file__).resolve().parent.parent109ENGINE_VERSION = "1.0.0"110MARK_TITLE = re.compile(r"SP BOUCHER \| ")111MARK_END = "END OF SP BOUCHER SOURCE HEADER"112RULE = "=" * 77113BOM = b"\xef\xbb\xbf"114KEY_COL = 19 # "Description : " — continuation lines are indented to this column115116TEMPLATE_FILE = {117 "SPB-FULL": "full.txt", "SPB-APPLE": "apple.txt", "SPB-RESEARCH": "research.txt",118 "SPB-LATEX": "latex.txt", "SPB-BIB": "bib.txt", "SPB-WEB": "web.txt",119 "SPB-INFRA": "infrastructure.txt", "SPB-MINIMAL": "minimal.txt",120}121122JS_EXT = {"js", "jsx", "mjs", "cjs", "ts", "tsx", "mts", "cts"}123JS_PRAGMA = re.compile(124 r"@ts-|@jest-environment|@vitest-environment|@jsx|@flow|eslint-|@format|prettier-|biome-|"125 r"deno-|istanbul|c8 ignore|v8 ignore|@refresh|@license|@preserve|@noflow")126PY_CODING = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*[-\w.]+")127LEGACY_KEYS = re.compile(128 r"^(Author|Auteur|Contact|File|Fichier|Path|Description|Role|Rôle|Purpose|Project|Projet|Module|Website|"129 r"Site|Email|E-mail|Courriel|Maintainer|Repository|Git|Created|Créé|Modified|Modifié)\s*:", re.I)130LEGACY_DESC = re.compile(r"^(Description|Role|Rôle|Purpose)\s*:", re.I)131LEGACY_CREATED = re.compile(r"(?:Created|Créé)\s*:\s*(\d{4}-\d{2}-\d{2})", re.I)132OWN_AUTHOR = re.compile(r"(Author|Auteur|Maintainer)\s*:\s*Simon-Pierre Boucher", re.I)133COPYRIGHT_WORD = re.compile(r"copyright|©|\(c\)\s*\d{4}|all rights reserved", re.I)134135136def load_config(root: Path = ROOT) -> dict:137 cfg = {}138 for name in ("identity", "languages", "exclusions"):139 with open(root / "config" / f"{name}.toml", "rb") as fh:140 cfg[name] = tomllib.load(fh)141 cfg["templates"] = {v: (root / "templates" / f).read_text(encoding="utf-8").splitlines()142 for v, f in TEMPLATE_FILE.items()}143 return cfg144145146# --------------------------------------------------------------------------- syntax147148@dataclass149class Syntax:150 style: str # line | block | html | notebook151 prefix: str = ""152 role: str = "source"153 lang: str = ""154155156def syntax_for(path: str, text: str | None, cfg: dict) -> tuple[Syntax | None, str]:157 """Return (syntax, reason). syntax is None when the format gets no in-file header."""158 name = path.rsplit("/", 1)[-1]159 langs = cfg["languages"]160 spec = None161 if name in langs["name"] or name.split(".")[0] in ("Dockerfile",):162 spec = langs["name"].get(name) or langs["name"]["Dockerfile"]163 ext = name.rsplit(".", 1)[-1].lower() if "." in name.strip(".") else ""164 if spec is None:165 if ext in langs["no_header"]:166 return None, "no-header-format: " + langs["no_header"][ext]167 spec = langs["ext"].get(ext)168 if spec is None:169 return None, "unsupported-format"170 style, prefix = spec["style"], spec.get("prefix", "")171 if style == "sniff-m": # .m is Objective-C or MATLAB172 objc = text is not None and re.search(r"^\s*(#import|@interface|@implementation|@import)\b", text, re.M)173 style, prefix = ("line", "//") if objc else ("line", "%")174 return Syntax(style, prefix, spec.get("role", "source"), spec.get("lang", "")), ""175176177# --------------------------------------------------------------------------- text model178179@dataclass180class Text:181 bom: bool182 lines: list[str] # keepends=True183 nl: str184185 @classmethod186 def from_bytes(cls, data: bytes) -> "Text":187 bom = data.startswith(BOM)188 text = (data[3:] if bom else data).decode("utf-8") # strict: never transcode189 lines = text.splitlines(keepends=True)190 nl = "\r\n" if lines and lines[0].endswith("\r\n") else "\n"191 return cls(bom, lines, nl)192193 def to_bytes(self) -> bytes:194 return (BOM if self.bom else b"") + "".join(self.lines).encode("utf-8")195196197def _bare(line: str) -> str:198 return line.rstrip("\r\n")199200201def prologue_end(lines: list[str], path: str, syn: Syntax) -> int | None:202 """Index of the first line that may follow the header. None => do not touch."""203 name = path.rsplit("/", 1)[-1]204 ext = name.rsplit(".", 1)[-1].lower() if "." in name else ""205 n, i = len(lines), 0206 L = lambda k: _bare(lines[k])207 if n and L(0).startswith("#!"):208 i = 1209 if n and L(0).startswith("<?xml"):210 return None211 if ext in ("py", "pyi"):212 while i < min(n, 2) and PY_CODING.match(L(i)):213 i += 1214 elif ext == "swift":215 if i < n and re.match(r"^//\s*swift-tools-version", L(i)):216 i += 1217 elif ext == "go":218 j = i219 while j < n and (L(j).startswith("//go:build") or L(j).startswith("// +build")):220 j += 1221 if j > i:222 i = j + 1 if j < n and not L(j).strip() else j223 elif syn.role in ("tex", "bib"):224 while i < n and (re.match(r"^%\s*!", L(i)) or L(i).startswith("%&")):225 i += 1226 elif name.split(".")[0] == "Dockerfile":227 while i < n and re.match(r"^#\s*(syntax|escape|check)\s*=", L(i)):228 i += 1229 elif ext in ("sh", "bash", "zsh"):230 if i < n and re.match(r"^#(compdef|autoload)\b", L(i)):231 i += 1232 elif ext in ("yaml", "yml"):233 if i < n and L(i).startswith("%"):234 return None235 elif ext in ("css", "scss"):236 if i < n and L(i).lstrip().lower().startswith("@charset"):237 i += 1 # @charset must be the very first bytes of a stylesheet238 elif ext in JS_EXT:239 while i < n:240 s = L(i).strip()241 if s.startswith("///") and ("<reference" in s or "<amd" in s):242 i += 1243 elif s.startswith("//") and JS_PRAGMA.search(s):244 i += 1245 elif s.startswith("/*"):246 j = i247 while j < n and "*/" not in L(j):248 j += 1249 blk = "".join(lines[i:j + 1])250 if j < n and JS_PRAGMA.search(blk) and not MARK_TITLE.search(blk) and L(j).rstrip().endswith("*/"):251 i = j + 1252 else:253 break254 else:255 break256 return i257258259def leading_comment(lines: list[str], i: int, syn: Syntax) -> tuple[int, int]:260 """Span [i, j) of the comment block that starts exactly at line i (may be empty)."""261 n = len(lines)262 if i >= n:263 return i, i264 s = _bare(lines[i])265 if syn.style == "html":266 if s.lstrip().startswith("<!--"):267 j = i268 while j < n and "-->" not in lines[j]:269 j += 1270 return i, min(j + 1, n)271 return i, i272 if syn.style == "block" and s.lstrip().startswith("/*"):273 j = i274 while j < n and "*/" not in lines[j]:275 j += 1276 return i, min(j + 1, n)277 prefix = syn.prefix if syn.style == "line" else "//"278 j = i279 while j < n:280 t = _bare(lines[j])281 if not t.startswith(prefix):282 break283 if prefix == "//" and t.startswith("///"): # Swift/Rust doc comment belongs to a declaration284 break285 if prefix == "#" and t.startswith("#!"):286 break287 j += 1288 return i, j289290291def _uncomment(line: str, syn: Syntax) -> str:292 """Text of a comment line without its delimiters. Only delimiters at the edges are removed:293 a path such as ``/api/*`` inside the text is content."""294 t = _bare(line).strip()295 if syn.style == "line" and t.startswith(syn.prefix):296 t = t[len(syn.prefix):]297 else:298 for opener in ("/**", "/*", "<!--"):299 if t.startswith(opener):300 t = t[len(opener):]301 break302 else:303 if t.startswith("//"):304 t = t[2:]305 elif t.startswith("*") and not t.startswith("*/"):306 t = t[1:]307 for closer in ("*/", "-->"):308 if t.rstrip().endswith(closer):309 t = t.rstrip()[:-len(closer)]310 return t[1:] if t.startswith(" ") else t311312313def find_spb_header(lines: list[str], start: int, syn: Syntax) -> tuple[int, int] | None:314 """Span [a, b) of an existing SP Boucher header beginning at line `start` (header lines only)."""315 a, j = leading_comment(lines, start, syn)316 block = lines[a:j]317 if not block or not MARK_TITLE.search("".join(block[:4])):318 return None319 for k, ln in enumerate(block):320 if MARK_END in ln:321 end = a + k + 1322 if end < j and _uncomment(lines[end], syn).strip() and set(_uncomment(lines[end], syn).strip()) <= {"="}:323 end += 1 # closing rule324 if syn.style in ("block", "html") and end < j and ("*/" in lines[end] or "-->" in lines[end]):325 end += 1 # comment terminator326 return a, end327 return None328329330def parse_header_fields(lines: list[str], syn: Syntax) -> dict:331 out, last = {}, None332 for ln in lines:333 t = _uncomment(ln, syn)334 m = re.match(r"^([A-Z][A-Za-z /]+?)\s*:\s(.*)$", t)335 if m and not t.startswith(" "):336 last = m.group(1).strip()337 out[last] = m.group(2).strip()338 elif last and t.startswith(" " * 8) and t.strip():339 out[last] += " " + t.strip()340 else:341 last = None342 return out343344345# --------------------------------------------------------------------------- rendering346347def _wrap(key_line_prefix: str, value: str, width: int = 77) -> list[str]:348 room = max(30, width - len(key_line_prefix))349 words, rows, cur = value.split(), [], ""350 for w in words:351 if cur and len(cur) + 1 + len(w) > room:352 rows.append(cur)353 cur = w354 else:355 cur = f"{cur} {w}".strip()356 rows.append(cur)357 return [key_line_prefix + rows[0]] + [" " * len(key_line_prefix) + r for r in rows[1:]]358359360def render_body(variant: str, values: dict, cfg: dict) -> list[str]:361 out: list[str] = []362 for raw in cfg["templates"][variant]:363 keys = re.findall(r"\{\{(\w+)\}\}", raw)364 if keys:365 if any(not str(values.get(k, "")).strip() for k in keys):366 continue # an unverified / unknown field is omitted, never invented367 m = re.match(r"^([^{]*:\s)\{\{(\w+)\}\}$", raw)368 if m:369 out.extend(_wrap(m.group(1), str(values[m.group(2)])))370 continue371 line = raw372 for k in keys:373 line = line.replace("{{%s}}" % k, str(values[k]))374 out.append(line.rstrip())375 else:376 out.append(raw.rstrip())377 # collapse blank runs left by omitted fields378 dedup: list[str] = []379 for ln in out:380 if ln == "" and dedup and dedup[-1] == "":381 continue382 dedup.append(ln)383 return dedup384385386def decorate(body: list[str], syn: Syntax, nl: str) -> list[str]:387 if syn.style == "block":388 rows = ["/**"] + [(" * " + b.replace("*/", "* /")).rstrip() for b in body] + [" */"]389 elif syn.style == "html":390 rows = ["<!--"] + [(" " + re.sub(r"-{2,}", lambda m: "=" * len(m.group()), b)).rstrip() for b in body] + ["-->"]391 else:392 rows = [(syn.prefix + " " + b).rstrip() if b else syn.prefix for b in body]393 return [r + nl for r in rows]394395396# --------------------------------------------------------------------------- analysis397398@dataclass399class Plan:400 action: str # insert | update | skip401 reason: str = ""402 a: int = 0403 b: int = 0404 sticky: dict = field(default_factory=dict)405 removed_legacy: str = ""406 sep: bool = False # a blank separator line is added after the header407 notes: list[str] = field(default_factory=list)408409410def _legacy_block(lines: list[str], a: int, j: int, syn: Syntax) -> tuple[bool, str, str]:411 """(replaceable, description, created). Replaceable only if every line is a known identity line."""412 desc, in_desc, ok, seen_text, created = "", False, True, False, ""413 for k in range(a, j):414 t = _uncomment(lines[k], syn).strip()415 if not t or set(t) <= set("=-*#~_─━ "):416 in_desc = False417 continue418 first_text, seen_text = not seen_text, True419 m = LEGACY_CREATED.search(t)420 if m:421 created = m.group(1)422 if LEGACY_KEYS.match(t):423 in_desc = bool(LEGACY_DESC.match(t))424 if in_desc:425 desc = t.split(":", 1)[1].strip()426 continue427 if in_desc:428 desc += " " + t429 continue430 if first_text and len(t) <= 70 and ":" not in t: # title line such as "ORIX Calc"431 continue432 ok = False433 return ok, desc.strip(), created434435436def py_docstring_summary(lines: list[str], i: int) -> str:437 k = i438 while k < len(lines) and (not lines[k].strip() or lines[k].lstrip().startswith("#")):439 k += 1440 if k >= len(lines):441 return ""442 m = re.match(r'^[rRuU]{0,2}("""|\'\'\')(.*)$', _bare(lines[k]))443 if not m:444 return ""445 q, rest = m.group(1), m.group(2)446 buf = rest447 if q not in rest:448 for ln in lines[k + 1:k + 6]:449 if buf.strip() and (not ln.strip() or q in ln):450 buf += " " + ln.split(q)[0].strip()451 break452 buf += " " + ln.strip()453 if q in ln:454 break455 buf = buf.split(q)[0].strip()456 first = re.split(r"(?<=[.!?])\s", buf, maxsplit=1)[0].strip()457 return first if 3 <= len(first) <= 240 else ""458459460def analyze(path: str, data: bytes, cfg: dict, syn: Syntax) -> tuple[Plan, Text | None]:461 ex = cfg["exclusions"]462 if b"\x00" in data[:8192]:463 return Plan("skip", "binary"), None464 if not data.strip():465 return Plan("skip", "empty-file"), None466 if data.startswith(b"version https://git-lfs"):467 return Plan("skip", "git-lfs-pointer"), None468 try:469 tx = Text.from_bytes(data)470 except UnicodeDecodeError:471 return Plan("skip", "manual-review: not valid UTF-8 (never transcoded)"), None472 lines = tx.lines473 if len(data) / max(1, len(lines)) > ex["files"]["max_avg_line"]:474 return Plan("skip", "minified-or-data"), None475 i = prologue_end(lines, path, syn)476 if i is None:477 return Plan("skip", "manual-review: leading directive forbids a comment here"), None478479 existing = find_spb_header(lines, i, syn)480 if existing:481 a, b = existing482 sticky = parse_header_fields(lines[a:b], syn)483 return Plan("update", "", a, b, sticky), tx484485 a, j = leading_comment(lines, i, syn)486 block = "".join(lines[a:j])487 head = block + "".join(lines[j:j + 5])488 for mk in ex["markers"]["generated"]:489 if mk in head:490 return Plan("skip", "generated-file"), None491 plan = Plan("insert", "", i, i)492 name = path.rsplit("/", 1)[-1]493 if syn.role == "tex":494 own_any = any(nm.lower() in "".join(lines[:80]).lower() for nm in ex["markers"]["own_names"])495 if name.endswith(".bst") and not own_any:496 return Plan("skip", "third-party-or-foreign-notice: bibliography styles are presumed third-party"), None497 if name.endswith((".cls", ".sty", ".bst")) and not own_any:498 top = "".join(ln for ln in lines[:80] if ln.lstrip().startswith("%"))499 if COPYRIGHT_WORD.search(top) or re.search(r"LaTeX Project Public License|LPPL|docstrip", top, re.I):500 return Plan("skip", "third-party-or-foreign-notice: preserved untouched"), None501 if block:502 own = any(nm.lower() in block.lower() for nm in ex["markers"]["own_names"])503 legal = COPYRIGHT_WORD.search(block) or any(504 mk in block for mk in ("SPDX-License-Identifier", "Licensed under", "Permission is hereby granted"))505 if legal and not own:506 return Plan("skip", "third-party-or-foreign-notice: preserved untouched"), None507 if legal and own:508 plan.notes.append("existing first-party copyright notice preserved below the header")509 elif OWN_AUTHOR.search(block):510 ok, desc, created = _legacy_block(lines, a, j, syn)511 if ok:512 plan.a, plan.b = a, j513 plan.removed_legacy = block514 plan.sticky["Description"] = desc515 if created:516 plan.sticky["Created"] = created517 plan.notes.append("legacy identity block replaced (description carried over)")518 else:519 plan.notes.append("legacy identity block kept (contains other content)")520 if name.endswith((".sh", ".bash", ".zsh")) or (lines and lines[0].startswith("#!") and syn.prefix == "#"):521 body = "".join(lines)522 if re.search(r"(sed|head|tail|awk|grep)\b[^\n|]*[\"']?\$(0|\{0\}|\{BASH_SOURCE)", body):523 return Plan("skip", "manual-review: script reads its own source by line"), None524 if not plan.sticky.get("Description") and name.endswith((".py", ".pyi")):525 d = py_docstring_summary(lines, plan.b)526 if d:527 plan.sticky["Description"] = d528 # A blank line is a paragraph break in LaTeX (fatal inside math or a table read with \\input):529 # LaTeX-family headers are never followed by an added blank line.530 plan.sep = syn.role not in ("tex", "bib") and plan.b < len(lines) and bool(lines[plan.b].strip())531 return plan, tx532533534def build(tx: Text, plan: Plan, variant: str, values: dict, cfg: dict, syn: Syntax) -> bytes:535 v = dict(values)536 for key, name in (("Description", "FILE_DESCRIPTION"), ("Created", "CREATION_DATE"),537 ("Last Modified", "MODIFICATION_DATE")):538 if plan.sticky.get(key):539 v[name] = plan.sticky[key]540 header = decorate(render_body(variant, v, cfg), syn, tx.nl)541 rest = tx.lines[plan.b:]542 sep = [tx.nl] if plan.sep else []543 return Text(tx.bom, tx.lines[:plan.a] + header + sep + rest, tx.nl).to_bytes()544545546def strip_header(data: bytes, path: str, cfg: dict, syn: Syntax, legacy: str = "", sep: bool = True) -> bytes | None:547 """Remove an SP Boucher header (and restore a recorded legacy block). None if no header."""548 tx = Text.from_bytes(data)549 i = prologue_end(tx.lines, path, syn)550 if i is None:551 return None552 span = find_spb_header(tx.lines, i, syn)553 if not span:554 return None555 a, b = span556 if sep and b < len(tx.lines) and not tx.lines[b].strip():557 b += 1558 restored = legacy.splitlines(keepends=True) if legacy else []559 return Text(tx.bom, tx.lines[:a] + restored + tx.lines[b:], tx.nl).to_bytes()560561562def sha(data: bytes) -> str:563 return hashlib.sha256(data).hexdigest()564565566# --------------------------------------------------------------------------- notebooks567568NB_KEY = "spboucher"569570571def notebook_apply(data: bytes, meta: dict) -> tuple[bytes | None, str]:572 """Add identity to notebook-level metadata. Refuses if a byte-exact round trip is impossible."""573 try:574 text = data.decode("utf-8")575 nb = json.loads(text)576 except Exception:577 return None, "manual-review: notebook is not valid UTF-8 JSON"578 for indent in (1, 2, 4, None):579 for ascii_ in (False, True):580 dumped = json.dumps(nb, indent=indent, ensure_ascii=ascii_)581 for tail in ("\n", ""):582 if dumped + tail == text:583 md = nb.setdefault("metadata", {})584 if md.get(NB_KEY) == meta:585 return data, "compliant"586 md[NB_KEY] = meta587 return (json.dumps(nb, indent=indent, ensure_ascii=ascii_) + tail).encode("utf-8"), "metadata"588 return None, "manual-review: notebook formatting cannot be preserved byte-for-byte"589