SPB Git

Repository Public

doctor.py 7.2 KB 154 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SP Boucher Development Standard7# File             : payload/standards/lib/spstd/doctor.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"""sp-dev-doctor — integrity and functional diagnosis of the SP Boucher development standard on this machine."""42import json43import os44import shutil45import sys46import tempfile4748from . import common as C4950CLAUDE = os.environ.get("SP_CLAUDE_DIR") or os.path.join(C.HOME, ".claude")51BINS = ("sp-header", "sp-git", "sp-security-scan", "sp-dev-doctor")52SKILLS = ("sp-source-header", "sp-git-governance", "sp-development-standard")53HOOKS = {"SessionStart": "hooks/sp-git-governance/session-start", "PreToolUse": "hooks/sp-security/pre-tool-use",54         "PostToolUse": "hooks/sp-source-header/post-tool-use", "SubagentStop": "hooks/sp-git-governance/subagent-stop",55         "Stop": "hooks/sp-git-governance/stop"}56BLOCK_START = "<!-- sp-development-standard:start -->"575859def main(argv=None):60    argv = argv if argv is not None else sys.argv[1:]61    as_json = "--json" in argv62    quick = "--quick" in argv63    res = []6465    def add(level, name, detail=""):66        res.append({"level": level, "check": name, "detail": detail})6768    add("ok" if sys.version_info >= (3, 8) else "fail", "python", "%d.%d.%d" % sys.version_info[:3])69    rc, out, _ = C.run(["git", "--version"])70    add("ok" if rc == 0 else "fail", "git", out.strip())71    add("ok", "standard version", C.version())72    for rel in ("identity.json", "VERSION", "source-header/TEMPLATE.md", "source-header/POLICY.md", "source-header/languages.json",73                "source-header/exclusions.json", "git-governance/POLICY.md", "git-governance/config.json"):74        p = os.path.join(CLAUDE, "standards", rel)75        add("ok" if os.path.isfile(p) else "fail", "standards/" + rel)76    for b in BINS:77        p = os.path.join(CLAUDE, "bin", b)78        add("ok" if os.access(p, os.X_OK) else "fail", "bin/" + b)79        add("ok" if shutil.which(b) else "warn", "PATH: " + b, shutil.which(b) or "not on PATH (use ~/.claude/bin/%s)" % b)80    for s in SKILLS:81        add("ok" if os.path.isfile(os.path.join(CLAUDE, "skills", s, "SKILL.md")) else "fail", "skill " + s)82    try:83        with open(os.path.join(CLAUDE, "settings.json"), encoding="utf-8") as f:84            settings = json.load(f)85    except (OSError, ValueError) as e:86        settings = {}87        add("fail", "settings.json", str(e))88    for event, rel in HOOKS.items():89        target = os.path.join(CLAUDE, rel)90        registered = any(rel in (h.get("command") or "") for g in (settings.get("hooks") or {}).get(event, []) for h in g.get("hooks", []))91        add("ok" if registered and os.access(target, os.X_OK) else "fail", "hook %s" % event,92            "" if registered else "not registered in ~/.claude/settings.json")93    try:94        with open(os.path.join(CLAUDE, "CLAUDE.md"), encoding="utf-8") as f:95            md = f.read()96    except OSError:97        md = ""98    add("ok" if BLOCK_START in md and "SP BOUCHER GLOBAL MANDATORY DEVELOPMENT STANDARD" in md else "fail",99        "CLAUDE.md permanent directive")100    # functional self-tests in a throw-away directory101    d = tempfile.mkdtemp(prefix="sp-dev-doctor-")102    try:103        from . import header as H104        from . import secscan as S105        p = os.path.join(d, "probe.ts")106        with open(p, "w") as f:107            f.write("export const x = 1;\n")108        r1 = H.process(p, "ensure", is_new=True)109        r2 = H.process(p, "ensure")110        with open(p) as f:111            t = f.read()112        add("ok" if r1["status"] == "added" and r2["status"] == "ok" and H.strip_header(t) == "export const x = 1;\n" else "fail",113            "header engine self-test", "%s/%s" % (r1["status"], r2["status"]))114        key = "sk-ant-" + "a1B2c3D4" * 5115        with open(os.path.join(d, "leak.txt"), "w") as f:116            f.write("ANTHROPIC_API_KEY=%s\n" % key)117        fnd, _ = S.scan(d, "files", [os.path.join(d, "leak.txt")])118        add("ok" if S.high(fnd) else "fail", "secret scanner self-test", "fictitious key %s" % ("detected" if S.high(fnd) else "MISSED"))119        from . import hooks as K120        calls = list(K.git_calls("cd /tmp && git push --force origin main", "/"))121        add("ok" if calls and K.destructive_reason(*calls[0]) else "fail", "destructive-git guard self-test")122    except Exception as e:123        add("fail", "self-tests", str(e))124    finally:125        shutil.rmtree(d, ignore_errors=True)126    if not quick:127        from . import gitgov as G128        be = G.Backend()129        try:130            be.exists("sp-dev-doctor-probe")131            add("ok", "SPB Git over SSH", be.local or be.host)132        except RuntimeError as e:133            add("warn", "SPB Git over SSH", "unreachable from this machine: %s" % str(e)[:120])134        code = be.web_status("")135        add("ok" if code == "200" else "warn", "SPB Git web", "%s → HTTP %s" % (be.web, code))136        for k in ("user.name", "user.email"):137            v = C.git_out(["config", "--global", k], C.HOME)138            add("ok" if v else "warn", "git " + k, v or "unset")139    fails = [r for r in res if r["level"] == "fail"]140    warns = [r for r in res if r["level"] == "warn"]141    if as_json:142        print(json.dumps({"version": C.version(), "host": os.uname().nodename, "ok": not fails, "fail": len(fails),143                          "warn": len(warns), "checks": res}, indent=2, ensure_ascii=False))144    else:145        print("SP Boucher development standard %s — %s" % (C.version(), os.uname().nodename))146        for r in res:147            print("  [%-4s] %-42s %s" % (r["level"], r["check"], r["detail"]))148        print("Result: %s (%d checks, %d failed, %d warnings)" % ("HEALTHY" if not fails else "BROKEN", len(res), len(fails), len(warns)))149    return 1 if fails else 0150151152if __name__ == "__main__":153    sys.exit(main())154
Files main
Menu

Theme