diff --git a/example/example.mk b/example/example.mk index 9dc15d8..618b443 100644 --- a/example/example.mk +++ b/example/example.mk @@ -74,7 +74,7 @@ EXAMPLE_INC = -I$(EXAMPLE_DIR) -I$(EXAMPLE_BUILD) -Isrc EXAMPLE_REAL_LIBS = build/google/libgoogle.a build/clients/libclients.a \ build/liboperability.a -.PHONY: example example-real-libs example-assets example-test example-clean example-locust +.PHONY: example-deploy example-verify deploy verify example example-real-libs example-assets example-test example-clean example-locust # Asset embedding is part of the build: example/assets (Chart.js included) # becomes generated C++ under build/example/gen via the MoloApp embedder. @@ -134,6 +134,32 @@ example-locust: example-clean: rm -rf $(EXAMPLE_BUILD) +# Deploy: loopback single binary (AGENTS.md "Deploy"). Restarts the server from +# build/ with a pid file; fails if it is not healthy within 15 s. Runs from +# the repo root so .env.json(.local) and example/static resolve. +EXAMPLE_PORT ?= 8080 +EXAMPLE_RUN = $(EXAMPLE_BUILD)/run + +example-deploy: example + mkdir -p $(EXAMPLE_RUN) + if [ -f $(EXAMPLE_RUN)/server.pid ] && kill -0 `cat $(EXAMPLE_RUN)/server.pid` 2>/dev/null; then \ + kill `cat $(EXAMPLE_RUN)/server.pid`; \ + for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 `cat $(EXAMPLE_RUN)/server.pid` 2>/dev/null || break; sleep 0.5; done; \ + fi + setsid nohup $(EXAMPLE_BUILD)/living-server $(EXAMPLE_PORT) --no-locust \ + > $(EXAMPLE_RUN)/server.log 2>&1 < /dev/null & echo $$! > $(EXAMPLE_RUN)/server.pid + ok=0; for i in `seq 1 30`; do \ + if curl -fsS http://127.0.0.1:$(EXAMPLE_PORT)/health > /dev/null 2>&1; then ok=1; break; fi; sleep 0.5; \ + done; \ + if [ $$ok -ne 1 ]; then echo "deploy: server not healthy in 15 s"; cat $(EXAMPLE_RUN)/server.log; exit 1; fi; \ + echo "deployed: http://127.0.0.1:$(EXAMPLE_PORT) pid `cat $(EXAMPLE_RUN)/server.pid`" + +example-verify: + python3 -I tools/verify_deploy.py http://127.0.0.1:$(EXAMPLE_PORT) + +deploy: example-deploy +verify: example-verify + # Root Makefile aggregation points (double-colon: safe with other parts). all:: example test:: example-test diff --git a/tools/release.py b/tools/release.py new file mode 100755 index 0000000..6f3f7d1 --- /dev/null +++ b/tools/release.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Release tool implementing AGENTS.md (Version bump, Commit, Tag). + +Stages (dry-run unless --apply): + prepare parse commits since the last tag, choose the bump, write VERSION + and the CHANGELOG.md entry, commit them. + tag create the annotated tag vMAJOR.MINOR.PATCH for the VERSION in the + tree. Run it only after deploy + verify were green (AGENTS.md: + failed verification blocks the tag). + +Rules: Conventional Commits `[(scope)][!]: `, subject max +100 chars, allowed types and scopes from AGENTS.md. Malformed commits are +counted and listed loudly and skipped before version analysis (history is +never rewritten). Bump: any `!` or BREAKING CHANGE -> MAJOR; else any feat -> +MINOR; else any fix -> PATCH; else no release. Max 20 changelog lines. +Stdlib only. +""" +import argparse +import re +import subprocess +import sys +from datetime import date +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TYPES = {"feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore"} +SCOPES = {"runtime", "security", "data", "routing", "realtime", "supervisor", + "clients", "cli", "workflow"} +SUBJECT_MAX = 100 +CHANGELOG_MAX_LINES = 20 +PATTERN = re.compile(r"^(?P[a-z]+)(\((?P[a-z]+)\))?(?P!)?: (?P.+)$") +SECTION = {"feat": "Features", "fix": "Fixes", "perf": "Performance"} + + +def git(*args, check=True): + r = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True) + if check and r.returncode != 0: + sys.exit(f"git {' '.join(args)} failed: {r.stderr.strip()}") + return r.stdout.strip() + + +def last_tag(): + tags = [t for t in git("tag", "--list", "v*.*.*", "--sort=-v:refname").splitlines() if t] + return tags[0] if tags else None + + +def commits_since(tag): + rng = f"{tag}..HEAD" if tag else "HEAD" + out = git("log", rng, "--format=%H%x1f%s%x1f%b%x1e") + items = [] + for rec in out.split("\x1e"): + rec = rec.strip("\n") + if not rec: + continue + h, subject, body = (rec.split("\x1f") + ["", ""])[:3] + items.append((h[:9], subject, body)) + return items + + +def classify(items): + ok, bad = [], [] + for h, subject, body in items: + m = PATTERN.match(subject) + reason = None + if not m: + reason = "not [(scope)][!]: " + elif m["type"] not in TYPES: + reason = f"type '{m['type']}' not allowed" + elif m["scope"] and m["scope"] not in SCOPES: + reason = f"scope '{m['scope']}' not allowed" + elif len(subject) > SUBJECT_MAX: + reason = f"subject over {SUBJECT_MAX} chars" + if reason: + bad.append((h, subject, reason)) + else: + breaking = bool(m["bang"]) or "BREAKING CHANGE" in body + ok.append((h, m["type"], m["scope"], m["desc"], breaking)) + return ok, bad + + +def choose_bump(ok): + if any(b for *_, b in ok): + return "major" + if any(t == "feat" for _, t, *_ in ok): + return "minor" + if any(t == "fix" for _, t, *_ in ok): + return "patch" + return None + + +def current_version(tag): + if tag: + return tuple(int(x) for x in tag[1:].split(".")) + return (0, 0, 0) + + +def bumped(v, kind): + major, minor, patch = v + if kind == "major": + return (major + 1, 0, 0) + if kind == "minor": + return (major, minor + 1, 0) + return (major, minor, patch + 1) + + +def changelog_entry(version, ok, bad): + lines = [f"## v{version} - {date.today().isoformat()}", ""] + body = [] + for key, title in SECTION.items(): + rows = [(s, d) for _, t, s, d, _ in ok if t == key] + if rows: + body.append(f"### {title}") + for scope, desc in rows: + body.append(f"- {scope + ': ' if scope else ''}{desc}") + brk = [(s, d) for _, _, s, d, b in ok if b] + if brk: + body.append("### Breaking changes") + body += [f"- {s + ': ' if s else ''}{d}" for s, d in brk] + room = CHANGELOG_MAX_LINES - len(lines) - 2 + if len(body) > room: + hidden = len(body) - (room - 1) + body = body[: room - 1] + [f"- ... and {hidden} more (see git log)"] + lines += body + if bad: + lines += ["", f"Skipped {len(bad)} commits not in Conventional Commit form."] + return "\n".join(lines) + "\n" + + +def prepare(apply): + if git("status", "--porcelain"): + if apply: + sys.exit("refusing: working tree is not clean") + print("note: working tree is not clean (a real run would refuse)") + tag = last_tag() + ok, bad = classify(commits_since(tag)) + print(f"last tag: {tag or '(none)'}; conformant commits: {len(ok)}; malformed: {len(bad)}") + for h, s, why in bad: + print(f" SKIPPED {h} {s[:70]!r}: {why}") + kind = choose_bump(ok) + if not kind: + print("no release: no feat, fix, or breaking commit") + return 0 + new = bumped(current_version(tag), kind) + version = ".".join(map(str, new)) + entry = changelog_entry(version, ok, bad) + print(f"bump: {kind} -> v{version}\n--- CHANGELOG entry ---\n{entry}") + if not apply: + print("dry run: nothing written (use --apply)") + return 0 + (ROOT / "VERSION").write_text(version + "\n") + path = ROOT / "CHANGELOG.md" + old = path.read_text() if path.exists() else "# Changelog\n\n" + head, _, rest = old.partition("\n\n") + path.write_text(head + "\n\n" + entry + "\n" + rest) + git("add", "VERSION", "CHANGELOG.md") + git("commit", "-m", f"chore(workflow): release v{version}\n\nCo-Authored-By: Claude Sonnet 5.5 ") + print(f"committed release v{version}; deploy, verify, then run: tools/release.py tag --apply") + return 0 + + +def tag(apply): + if git("status", "--porcelain"): + sys.exit("refusing: working tree is not clean") + version = (ROOT / "VERSION").read_text().strip() + name = f"v{version}" + if git("tag", "--list", name): + sys.exit(f"refusing: tag {name} already exists") + print(f"tag {name} at {git('rev-parse', '--short', 'HEAD')}") + if not apply: + print("dry run: no tag created (use --apply)") + return 0 + git("tag", "-a", name, "-m", f"Release {name}") + print(f"created annotated tag {name}") + return 0 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("stage", choices=["prepare", "tag"]) + ap.add_argument("--apply", action="store_true", help="write (default is dry run)") + a = ap.parse_args() + return prepare(a.apply) if a.stage == "prepare" else tag(a.apply) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/verify_deploy.py b/tools/verify_deploy.py new file mode 100755 index 0000000..018c35d --- /dev/null +++ b/tools/verify_deploy.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Verify a running living-server (AGENTS.md "Verify live"). Any red step +halts with a non-zero exit. Stdlib only. + +Steps: health probe, metrics scrape, index load with the 360px markup checks, +then GET the first 10 matrix routes (2xx/3xx; 401 for /auth/me by design). +The 360px check is on markup and CSS (viewport meta, collapsing nav rule), +not on a rendered browser. +""" +import re +import sys +import urllib.error +import urllib.request + +BASE = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8080" +TIMEOUT = 15 +red = [] + + +def get(path): + req = urllib.request.Request(BASE + path, headers={"User-Agent": "verify-deploy/1"}) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + return r.status, r.read().decode("utf-8", "replace") + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace") + except Exception as e: # connection refused, timeout + return 0, str(e) + + +def step(name, ok, detail=""): + print(f"{'ok ' if ok else 'RED '} {name}{(': ' + detail) if detail else ''}") + if not ok: + red.append(name) + + +code, body = get("/health") +step("health probe", code == 200 and '"status":"ok"' in body.replace(" ", ""), f"{code} {body[:60]}") + +code, body = get("/metrics") +lines = [l for l in body.splitlines() if l and not l.startswith("#")] +step("metrics scrape", code == 200 and len(lines) > 0 and all(len(l.split()) >= 2 for l in lines[:20]), + f"{code}, {len(lines)} samples") + +code, index = get("/") +step("index loads", code == 200 and "", index) +top = [h for h in hrefs if h.startswith("/")][:10] +step("matrix has routes", len(top) >= 10, f"{len(top)} found") +for route in top: + code, _ = get(route) + ok = 200 <= code < 400 or (route.startswith("/auth/me") and code == 401) + step(f"route {route}", ok, str(code)) + +code, body = get("/google/status") +print(f"info google: {code} {body[:120]}") + +if red: + print(f"\nVERIFY FAILED: {len(red)} red step(s): {', '.join(red)}") + sys.exit(1) +print("\nVERIFY OK")